Summary
In the previous articles, I did not elaborate on the data provider core object, because I would like to give you a good idea of some basic concepts before I can explain these objects. In the previous article, "You Must know the ADO (c) connection string, you underestimate it," I explained in detail the connection string, I believe everyone and I just as aware of its importance. If the connection string is the key to opening the data source, what I'm going to talk about today is how to use the key to open the door to the data source. As the first core object of data provider, connection objects shoulder the burden of connecting data sources. Let's get to know the heavyweight here!
Directory
- Understanding Connection Objects
- Several methods that must be mastered
- Several properties that must be mastered
- Talk about ConnectionState.
- Example: SqlConnection object connecting to SQL Server
- Write elegant and Secure code
1. Understanding Connection Objects
The connection object, as the name implies, represents a connection to a particular data source . If the data source is compared to the gate, then the connection string is the key, and the connecting object is the person holding the key to open the door. For ADO, different data sources correspond to different connection objects. The specific Connection object is the following table:
Name |
Name space |
Describe |
SqlConnection |
System.Data.SqlClient |
Represents a Connection object to SQL Server |
OleDbConnection |
System.Data.OleDb |
Represents a Connection object to an OLE DB data source |
OdbcConnection |
System.Data.Odbc |
Represents a Connection object to an ODBC data source |
OracleConnection |
System.Data.OracleClient |
Represents a Connection object to the Orale database |
Regardless of the connection object, it inherits from the DbConnection class. Let's look at the implementation structure of the DbConnection class:
IDbConnection, IDisposable
From above, we can see that DbConnection is an abstract base class and inherits the Compoent,idbconnection,idisposable class. Because the DbConnection class is an abstract base class, it cannot be instantiated. The DbConnection class encapsulates a number of important methods and properties, and I'll cover several important methods and properties in detail below.
2. Several methods that must be mastered
open: ConnectionString . > Open the database connection using the settings specified by ConnectionString .
dispose: Component . > release all resources used by Component .
Close: Close the connection to the database. This method is the preferred method for closing any open connections. The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if the connection pool is disabled.
3. Several properties that must be mastered
Database : Gets the name of the current database after the connection is opened, or gets the names of the databases specified in the connection string before the connection is opened.
DataSource: Gets the name of the database server to connect to.
ConnectionTimeout: Gets the time to wait before terminating an attempt and generating an error when the connection is established.
ConnectionString: Gets or sets the string used to open the connection.
State : gets a string that describes the status of the connection.
4. Talk about ConnectionState
As we know above, theState property describes the current status of the connection to the data source. ConnectionState is an enumeration type. It includes the following members:
Closed: The connection is in a closed state.
Open: The connection is open.
connecting: The connection object is connecting to the data source.
EXECUTING:  The connection object is executing the command.
fetching: The connection object is retrieving data.
Broken: the connection to the data source was interrupted.
5. Example: SqlConnection object connecting to SQL Server
With so much theoretical knowledge, here's an example of connecting to SQL Server! The code is as follows:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data;
6 using System.Data.SqlClient;
7
8 namespace Connection
9 {
Ten class Program
11 {
A static void Main (string[] args)
13 {
14//Construct connection string
SqlConnectionStringBuilder connstr = new SqlConnectionStringBuilder ();
Connstr.datasource = @ ". \SQLExpress";
Connstr.initialcatalog = "Master";
Connstr.integratedsecurity = true;
19
SqlConnection conn = new SqlConnection ();//Create Connection object
Conn. ConnectionString = connstr.connectionstring;//Setting the connection string
22
Conn. Open ();//Opening connection
24
IF (Conn. state = = ConnectionState.Open)
26 {
Console.WriteLine ("Database is linked.");
Console.WriteLine ("\ndatasource:{0}", Conn. DataSource);
Console.WriteLine ("Database:{0}", Conn. Database);
Console.WriteLine ("Connectiontimeout:{0}", Conn. ConnectionTimeout);
31}
32
Conn. Close ();//Closed connection
Conn. Dispose ();//Release resources
35
IF (Conn. state = = connectionstate.closed)
37 {
Console.WriteLine ("\ndatabase is closed.");
39}
40
Console.read ();
42}
43}
44}
Results:
6. Write elegant and Secure Code (1) Add Try...catch block
We know there may be exceptions when connecting to the database, so we need to add exception handling. For C #, typical exception handling is to add Try...catch blocks of code. The finially is optional. Finially is a block of code that executes regardless of whether the code has an exception. and The database connection resources, is very valuable . Therefore, we should make sure that after the connection is opened, the connection and the resource release should be closed, regardless of whether an exception occurs. Therefore, we must call the Close method in the Finially statement block to close the database connection.
1 SqlConnection conn = new SqlConnection (CONNSTR);
2 Try
3 {
4 Conn. Open ();
5}
6 catch (Exception ex)
7 {
8 ;//todo
3 ·
Ten finially
11 {
Conn. Close ();
13}
(2) using Use statements
Another elegant method is to use the using statement. If you're not familiar with using syntax, I'll just say a few more words. The USE statement works by ensuring that resources are used, and releasing them quickly. the using statement helps reduce potential problems with unexpected run-time errors, and it neatly wraps the use of resources. Specifically, it does the following:
- Allocate resources.
- Put the statement in the try block.
- Create a Dispose method of the resource and put it in the finally block.
Therefore, the above statement is equivalent to:
1 using (SqlConnection conn = new SqlConnection (CONNSTR))
2 {
3 ;//todo
4}
Article posted: http://liuhaorain.cnblogs.com
Ado. NET Getting Started Tutorial (iv) Taste connection objects