The SqlConnection class is used to connect the database (SQL Server). In order to develop good programming habits, the reader should use the three-tier architecture programming idea to complete project development. Place operations related to the background database in a class.
The main program code is as follows.
In the class file ClsDBControl, you can customize a ConDB method to open a connection to the database and return a SqlConnection object. The program code is as follows:
Private SqlConnection con;
Public SqlConnection ConDB ()
{
Con = new SqlConnection ("server =.; uid = sa; pwd =; database = DB_ADONET ");
If (con. State = ConnectionState. Closed)
{
Con. Open ();
}
Return con; // return the SqlConnection object
} In the presentation layer, you can call the ConDB method to connect the database. The program code is as follows:
Private void button#click (object sender, EventArgs e)
{
ClsDB. ClsDBControl Con = new OptDB. ClsDB. ClsDBControl ();
SqlConnection conTry = Con. ConDB ();
MessageBox. Show (conTry. State. ToString (); // display the status of the current connection object
} Note: when calling the ConDB method of the data layer, You need to introduce the SqlClient namespace. The program code is as follows:
Using System. Data