C# development-connect to the database (15.4)

I. Overview

The Connection class in C# language is the first class to be used when ADO.NET components connect to the database, and it is also the first step to access the database through programming. Next, let’s take a look at the common properties and methods in the Connection class, and how to connect to the SQL Server database.

<!--more-->

Two Connection class overview

The Connection class uses different namespaces according to the data to be accessed and the access method, and the class name is slightly different. The common attributes and methods provided in the SqlConnection class are as follows

Attribute or method Description
SqlConnection() No-parameter construction method
SqlConnection(string connectionstring) The construction method with parameters, the database connection string as a parameter
Connectionstring Properties, get or set the connection string of the database
State Property, get the current database state, the enumeration type Connectionstate provides its value
ConnectionTimeout Property to get the time to wait before terminating the attempt and generating an error when trying to connect
DataSource Property to get the instance name of the SQL Server to be connected
Open() Method to open a database connection
Close() Method to close the database connection
BeginTransaction() Method to start a database transaction

Three use the Connection class to connect to the database

There are many ways to write database connection strings, here are two commonly used methods

3.1 Method 1

server = server name / database instance name; uid = login name; pwd = password; database = database name

among them:

  • server: Used to specify the name of the database instance to access the database. The server name can be replaced by the IP address or the computer name where the database is located. If the local database is accessed, "." can be used instead. For example, if you are connecting to the default database of the machine, you can write "server=."

  • uid: The user name used to log in to the specified SQL Server database instance, which is equivalent to the user name used when logging in to the database in SQL Server authentication mode, such as the sa user

  • pwd: the password corresponding to the uid user

  • database: To access the database name under the database instance

3.2 The second way

Data Source = server name\ database instance name; Initial Catalog = database name; User ID = user name; Password = password

among them:

  • Data Source: Same as the wording of the database attribute in the first connection string, it is used to specify the server name and database instance name where the database is located. If the connection is the default database instance of the machine, write "Data Source=." form

  • Initial Catalog: Same as the wording of the database attribute in the first connection string wording, used to specify the database name under the database instance in the Data Source

  • User ID: Same as the uid attribute in the first connection string writing method, used to specify the user name to log in to the database

  • Password: Same as the pwd attribute in the first connection string writing method, used to specify the password corresponding to the User ID user name.

Four connection related operations

After completing the preparation of the database connection string, you can use the SqlConnection class to connect to the database, which is completed in the following 3 steps

4.1 Create an instance of the SqlConnection class

For the SqlConnection class, two construction methods are provided in the above table. Usually, the construction method with a string parameter is used to set the connection string of the database to create its instance. The statement form is as follows.

SqlConnection connection object name = new SqlConnection (database connection string);

4.2 Open database connection

After creating an instance of the SqlConnection connection class, the database is not connected. You need to use the Open method of the connection class to open the database connection.

When using the Open method to open a database connection, if the connection string of the database is incorrect or the service of the database is closed, there will be an exception related to the failure to open the database, so exception handling is required to handle the exception.

The form of the statement to open the database connection is as follows.

Connection object name.Open();

4.3 Close the database connection

After the operation of the database is finished, the connection to the database should be disconnected to save the resources of the database connection.

The statement form to close the database connection is as follows.

Connection object name.Close();

If exception handling is used when opening a database connection, put the statement that closes the database connection into the finally statement of exception handling, so as to ensure that the database connection will be disconnected regardless of whether an exception occurs to release resources

In addition to using exception handling to release resources, you can also use using to release resources. The specific sentence is as follows.

using(SqlConnection connection object name = new SQLConnection(database connection string)) 
{ 
    //Open the database connection 
    //Statement for closing the database operation 
}

There are two main uses of the using keyword, one is to refer to the namespace, and the other is to create an unmanaged resource object.

Resources on the .NET platform are divided into managed resources and unmanaged resources. Managed resources are managed by the .NET framework directly to manage their resources in memory, such as declared variables; unmanaged resources cannot be directly managed by the .NET framework Management requires the use of code to release resources, such as database resources and operating system resources.

Five examples

5.1 Instance 1 creates a connection with the native SQL Server database and uses exception handling

5.1.1 Analysis

The user name used to connect to the SQL Server database is sa, the password is pwdpwd, and the connected database is test

5.1.2 Create database test

Open Microsoft SQL Server Management Studio, after logging in, right-click on the database, create a new database and enter the name of the created database

 

5.1.3 Code

Create a Windows Form application, and place a button on the form, add the following code in the button click event

private void button1_Click(object sender, EventArgs e) 
 { 
   //Write the database connection string 
   //string connStr = "Data source=.;Initial Catalog=test;User ID=sa;Password=root"; 
   string connStr = "Data source= .;Initial Catalog=test;Integrate Security = True"; 
   //var connStr = "server=.;uid=sa;pwd=root;database=test"; 
   //Create an instance of 
    SqlConnection SqlConnection conn = null; 
    try 
      { 
         conn = new SqlConnection(connStr); 
         conn.Open(); 
         MessageBox.Show("Database connection succeeded!"); 
       } 
      catch (Exception ex) 
      { 
           MessageBox.Show("Database connection failed!" + ex.Message); 
      }
      finally
      {
         if (conn != null) 
         { 
            //Close the database 
            conn.Close(); 
          } 
       } 
}

5.1.4 Effect picture

 

5.2 Example 2 Use the using keyword to release resources on the basis of the previous example.

5.2.1 Code

private void button1_Click(object sender, EventArgs e) 
{ 
   //Write the database connection string 
   //string connStr = "Data source=.;Initial Catalog=test;User ID=sa;Password=root"; 
   //string connStr = "Data source=.;Initial Catalog=test;Integrate Security = True"; 
   var connStr = "server=.;uid=sa;pwd=root;database=test"; 
   //Create an instance of SqlConnection 
          
   try 
      { 
         using (SqlConnection conn=new SqlConnection(connStr)) 
         conn.Open(); 
         MessageBox.Show("Database connection succeeded!"); 
       } 
       catch (Exception ex) 
       { 
          MessageBox.Show("Database connection failed!" + ex.Message); 
       } 
 }

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/108015150