C Programming to Connect SQL SERVER Database Instance Detailed Explanation

  • 2021-08-31 08:55:24
  • OfStack

This article describes the example of C # programming to connect SQL SERVER database. Share it for your reference, as follows:

First, establish a database name named "Exercise" in SQL SEVER, and establish a table named "lianxi" under this database. OK, now start writing the code.

In FORM1, drag 1 DATAGIRDVIEW to display the table, and put 1 BUTTON to perform the operation. Add Namespace

using system.data.sqlclient;


private void button1_Click(object sender, EventArgs e)
{
  string con, sql;
  con = "Server=.;Database=Exercise;Trusted_Connection=SSPI";
  sql = "select * from lianxi";
  SqlConnection mycon = new SqlConnection(con);
mycon.Open();
SqlDataAdapter myda = new SqlDataAdapter(sql, con);
DataSet myds = new DataSet();
myda.Fill(myds, "lianxi");
dataGridView1.DataSource = myds.Tables["lianxi"];
mycon.Close();

Let's explain the statements on each line. (In fact, the main thing is to explain the string parameters of the connection.)

The mechanism of connecting SQL Server is not much different from the mechanism of connecting Access, except that different parameters in Connection object and connection string are changed.

First, the namespace used to connect SQL Server is not "System. Data. OleDb", but "System. Data. SqlClient".

The second is his connection string, which is introduced by one parameter (note: the parameters are separated by semicolons):

The general format is "Server=; DataDase=; user id=; password=;"

Since the password and user name of SQL SERVER server were not set on my machine, Windows was selected for login when installing, so there were no user id and password, and "Trusted_Connection=SSPI" was used instead of the two items. If there is a password and user name, the format is as follows:

"user id=sa": The authenticated user name of the connection is sa. He also has an alias "uid", so we can also write this sentence as "uid=sa".
"password=": The authentication password for the connection is empty. His alias is "pwd", so we can write it as "pwd=".
"DataBase = Exercise" refers to the server you set up.
"Server=.: This dot means native and can also be written as server=localhost,

The rest is no different from Access! (For the connection of ACCESS, please refer to the previous article "Detailed explanation of connecting ACCESS database instance by C # programming")

I hope this article is helpful to everyone's C # programming.


Related articles: