


create instanace of database connection + database + " Persist Security Info=True User ID=" + username + " Password=" + password String connString = Source=" + datasource + " Initial Catalog=" Var username = "sa" //username of server to connect Var database = "Students" //your database name Here is the console application example to connect to local database and open the connection using System Ĭonsole.WriteLine("Getting Connection. Once the Database activities is over, Connection should be closed and release the Data Source resources When the connection is established, SQL Commands will execute with the help of the Connection Object and retrieve or manipulate the data in the database. If you have a named instance of SQL Server, you'll need to add that as well. Initial Catalog=DatabaseName User ID=UserName Password=Password" Here is the sample SQL server connection string should look like connetionString="Data Source=ServerName The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. The SqlConnection Object is used to handle the part of physical communication between the C# application and the SQL Server Database.Īn instance of the SqlConnection class in C# has supported the Data Provider for SQL Server Database. Now to connect to SQL Server, we need to create an instance of SQLConnection and pass a connection string to it. Once the Console Application template is generated by Visual Studio, Navigate to Program.cs from Solution Explorer ( You can open it by Clicking "View"-> "Solution Explorer").

In this article, I will provide your working example to create a database connection in C# using console application example or you can say an example, to connect to SQL Server using C#, you can use same C# code in Console application or Windows or ASP.NET Web-Form/MVC, we are using Console application example in this post.įirst of all, open your Visual Studio and navigate to File->New->Project -> Select "Windows" from left pane and select "Console app" from the right pane, provide a name to your project and click "OK"
