C # connect to the SQL Server code
Using System. Data;
Using System. Data. SqlClient;
//...
String strConnection = "user id = sa; password = ;";
StrConnection = "initial catalog = Northwind; Server = YourSQLServer ;";
StrConnection = "Connect Timeout = 30 ";
SqlConnection objConnection = new SqlConnection (strConnection );
//...
ObjConnection. Open ();
ObjConnection. Close ();
//...
Detailed explanation:
There is no major difference between the mechanism for connecting to the SQL Server database and the Access mechanism, but it only changes the different parameters in the Connection object and Connection string.
First, the namespace used to connect to SQL Server is not "System. Data. OleDb", but "System. Data. SqlClient ".
The second is his connection string. We will introduce them one by one (note: the parameters are separated by semicolons ):
"User id = sa": the authenticated user name used to connect to the database is sa. It also has an alias "uid", so we can also write this statement as "uid = sa ".
"Password =": The verification password for connecting to the database is blank. Its alias is "pwd", so we can write it as "pwd = ".
Note that your SQL Server must have a user name and password set to log on. Otherwise, you cannot log on using this method.
If your SQL Server is set to Windows logon, you do not need to use the "user id" and "password" methods to log on here, you need to use "Trusted_Connection = SSPI" to log on.
"Initial catalog = Northwind": the data source used is "Northwind". Its alias is "Database ",
This sentence can be written as "Database = Northwind ".
"Server = YourSQLServer": Use a Server named "YourSQLServer. its alias is "Data Source", "Address", "Addr ". if the local database is used and the Instance name is defined, you can enter "Server = (local) Instance name". If it is a remote Server) "Replace with the name or IP address of the remote server.
"Connect Timeout = 30": the connection Timeout is 30 seconds.
Here, the constructor used to create a connection object is SqlConnection.