C # connect to the SQL Server database,
C # connect to the SQL Server database. Here we will briefly introduce common methods for connecting to the SQL Server database. The database to be connected is the local SQL Server, the official Northwind database. Create a form application in VS2010 and add a button to verify that the database is connected successfully. Compile the button background Code as follows:
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. data. sqlClient; namespace CSharpConnectSQL {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void btnCSharpConnectSQL_Click (object sender, EventArgs e) {string strConnection = "Server = localhost;"; strConnection + = "initial catalog = Northwind;"; strConnection + = "user id = sa;"; strConnection + = "password = 123 ;"; strConnection + = "Connect Timeout = 5"; bool canConnectSQL = false; using (SqlConnection objConnection = new SqlConnection (strConnection) {try {objConnection. open (); canConnectSQL = true; objConnection. close ();} catch {} if (canConnectSQL) MessageBox. show ("database connection Successful! "," Crazygolf Alert "); else {MessageBox. Show (" database connection failed! "," Crazygolf Alert ");}}}}}Note the following:
- The Server property value is the address of the database. You can use localhost or dot (.) locally, or enter an IP address. If remote access is required, the remote access function should be activated.
- The initial catalog attribute value is the name of the database to be connected, which is replaced by Northwind.
- The user id and password are repeated.
- The value of Connect Timeout is the connection Timeout. When the Open () method of the database is called, the program becomes congested. During this period, the database is continuously opened based on the connection string we wrote. If the network is different or the Server or other fields are incorrect, there is a risk of latency or even crash, so the write timeout is smaller.
Run the program and click the button. You can see: