C-sharp, how to create a SQL connection

66

By hoangnam

SqlClient Connection in C#

This article will show you how to create a SQL Client connection in C#. A connection is needed when an application interface or web interface want to connect to the MS SQL database. System.Data.SqlClient namespace is needed to create a SQL connection.

We are using the connection builder to do this so first create a connection builder.

SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();

connBuilder.IntegratedSecurity = false; //Set this to false if we want to use window authentication

connBuilder.DataSource = @".\SQLExpress";

connBuilder.InitialCatalog = "TestDb"; //Your database name

SqlConnection conn = new SqlConnection(connBuilder.ConnectionString);

We now have a connection using the above database information.

Using the connection:

conn.OpenConnection();

//You can use the connection to query, update, insert, etc..

conn.CloseConnection(); //Make sure you remember to close the connection

Bhausaheb Funde 13 months ago

System.Data.SqlClient;

SqlConnection conn = new SqlConnection("Data Source=servername;Initial Catalog=DatabaseName;User ID=sa;password=pwd;Integrated Security=True");

conn.open();

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    • No HTML is allowed in comments, but URLs will be hyperlinked
    • Comments are not for promoting your Hubs or other sites

    Please wait working