ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

How to Connect SQL Server to C#

connectionSQLoutPutPI connect SQL Server

 

This time, I will teach you how to connect SQL Server 2005 to C# using Microsoft Visual Studio 2008. With this, you can create a connection between C#.net and SQL Server 2005 database.

 

Let’s begin:

 

First, open Visual Studio 2008 and create a new project.

connectionSQLFig1

 

The window of “New Project” will appear. In the New Project window, select “Visual C#” and create a new Windows Form Application.

connectionSQLFig2

 

Do the form just like this.

connectionSQLFig3

Now, double click a button and do the following codes for the connection between SQL Server and Visual C#.

Note: Put using System.Data.SqlClient; above the namespace to access sql server library.

private void button1_Click(object sender, EventArgs e)
 {
 //initialize sql connection
 SqlConnection con = new SqlConnection();

//set a connection string
 con.ConnectionString = "Data Source=.\\SQLEXPRESS;Database=testdb;trusted_connection=true;";

//opening connection
 con.Open();

//validating connection
 if (con.State == ConnectionState.Open)
 {
 button1.Text = "Disconnect Me";
 label2.Text = "Connected";
 con.Close();

}
 else
 {
 button1.Text = "Connect Me";
 label2.Text = "Disconnected";
 }
 }

 

Output:

connectionSQLoutPutPI

 

You can do this following example:

private void button1_Click(object sender, EventArgs e)
 {
 //initialize sql connection
 SqlConnection con = new SqlConnection();

//set a connection string
 con.ConnectionString = "Server=.\\SQLEXPRESS;" +
 "User Instance=true;" +
 "Integrated Security=true;" +
 "AttachDbFilename=" + Application.StartupPath + "\\testdb.mdf;";
 //original Path:
 //C:\Users\Janobe\Documents\Visual Studio 2008\Projects\SQLconnect\SQLconnect\bin\Debug

//opening connection
 con.Open();

//validating connection
 if (con.State == ConnectionState.Open)
 {
 button1.Text = "Disconnect Me";
 label2.Text = "Connected";
 con.Close();

}
 else
 {
 button1.Text = "Connect Me";
 label2.Text = "Disconnected";
 }
 }

Reminder: You must put your database file(testdb.mdf) inside the bin folder of your project to make this second example work.

Output:

connectionSQLoutPutPI

 

For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages. You can contact me @ :
Email – jannopalacios@gmail.com
Mobile No. – 09305235027 – tnt

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!