Open Database Connection (SQL Server)

Source: Internet
Author: User

 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.