Using a SqlConnection Object to Connect to a SQL Server Database phần 2

Chia sẻ: Tuan Nghia | Ngày: | Loại File: PDF | Số trang:7

0
54
lượt xem
17
download

Using a SqlConnection Object to Connect to a SQL Server Database phần 2

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

The output from this program is as follows: count = 1 Milliseconds = 101 mySqlConnection.State = Open count = 2 Milliseconds = 0 mySqlConnection.State = Open count = 3 Milliseconds = 0 mySqlConnection.State = Open count = 4 Milliseconds

Chủ đề:
Lưu

Nội dung Text: Using a SqlConnection Object to Connect to a SQL Server Database phần 2

  1. The output from this program is as follows: count = 1 Milliseconds = 101 mySqlConnection.State = Open count = 2 Milliseconds = 0 mySqlConnection.State = Open count = 3 Milliseconds = 0 mySqlConnection.State = Open count = 4 Milliseconds = 0 mySqlConnection.State = Open count = 5 Milliseconds = 0 mySqlConnection.State = Open count = 6 Milliseconds = 0 mySqlConnection.State = Open count = 7 Milliseconds = 0 mySqlConnection.State = Open count = 8 Milliseconds = 0 mySqlConnection.State = Open count = 9 Milliseconds = 0 mySqlConnection.State = Open count = 10 Milliseconds = 0 mySqlConnection.State = Open Note Your results might differ from those here. As you can see, the time to open the first connection is relatively long compared with the subsequent ones. This is because the first connection makes the actual connection to the database. When it is closed, it's stored in the connection pool. When the connection is then opened again, it's retrieved from the pool, and this retrieval is very fast. Getting the State of a Connection Object
  2. The state of a connection enables you to know the progress of your connection request to the database; two examples of states are open and closed. You use the Connection object's State property to get the current state of the connection to the database. The State property returns a constant from the ConnectionState enumeration. Note An enumeration is a list of numeric constants, each of which has a name. Table 7.4 lists the constants defined in the ConnectionState enumeration. Table 7.4: ConnectionState CONSTANTS CONSTANT DESCRIPTION NAME Broken The Connection is broken. This can happen after you've opened the Connection object. You can close the Connection and reopen it. Closed The Connection is closed. Connecting The Connection is establishing access to the database. Executing The Connection is running a command. Fetching The Connection is retrieving information from the database. Open The Connection is open. Note In version 1 of ADO.NET, only the Open and Closed states are used. The other states will be used in later versions. An example of using the State property would be to check if your Connection object is currently open before calling its Open() method. You might need to do that if you have a complex application and you're using a Connection object created somewhere else in the application: you might not know the current state of that Connection object and you don't want to call the Open() method on an already open Connection because that will raise an exception. The following example uses the State property to check if mySqlConnection is closed before opening it: if (mySqlConnection.State == ConnectionState.Closed) { mySqlConnection.Open(); } As you'll learn in the next section, you can use the StateChange event to monitor changes in a Connection object's state.
  3. Using Connection Events The Connection classes have two useful events: StateChange and InfoMessage. You'll see how to use these events next. The StateChange Event The StateChange event fires when the state of your connection is changed, and you can use this event to monitor changes in the state of your Connection object. The method that handles an event is known as an event handler. You call this method when a particular event is fired. All event handler methods must return void and accept two parameters. The first parameter is an object (of the class System.Object), and it represents the object that raises the event. Note The System.Object class acts as the base class for all classes. In other words, all classes are ultimately derived from the System.Object class. The second parameter is an object of a class that is derived from the System.EventArgs class. The EventArgs class is the base class for event data and represents the details of the event. In the case of the StateChange event, this second object is of the StateChangeEventArgs class. The following example defines a method named StateChangeHandler to handle the StateChange event. You'll notice that the second parameter to this method is a StateChangeEventArgs object. You get the original state of the connection using this object's OriginalState property, and you get the current state using the CurrentState property. public static void StateChangeHandler( object mySender, StateChangeEventArgs myEvent ) { Console.WriteLine( "mySqlConnection State has changed from "+ myEvent.OriginalState + "to "+ myEvent.CurrentState ); } To monitor an event, you must register your event handler method with that event. For example, the following statement registers the StateChangeHandler() method with the StateChange event of the mySqlConnection object:
  4. mySqlConnection.StateChange += new StateChangeEventHandler(StateChangeHandler); Whenever the StateChange event fires, the StateChangeHandler() method will be called, which displays the original and current state of mySqlConnection. Listing 7.3 illustrates the use of the StateChange event. Listing 7.3: STATECHANGE.CS /* StateChange.cs illustrates how to use the StateChange event */ using System; using System.Data; using System.Data.SqlClient; class StateChange { // define the StateChangeHandler() method to handle the // StateChange event public static void StateChangeHandler( object mySender, StateChangeEventArgs myEvent ) { Console.WriteLine( "mySqlConnection State has changed from "+ myEvent.OriginalState + "to "+ myEvent.CurrentState ); } public static void Main() { // create a SqlConnection object SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); // monitor the StateChange event using the StateChangeHandler() method mySqlConnection.StateChange += new StateChangeEventHandler(StateChangeHandler); // open mySqlConnection, causing the State to change from Closed
  5. // to Open Console.WriteLine("Calling mySqlConnection.Open()"); mySqlConnection.Open(); // close mySqlConnection, causing the State to change from Open // to Closed Console.WriteLine("Calling mySqlConnection.Close()"); mySqlConnection.Close(); } } The output from this program is as follows: Calling mySqlConnection.Open() mySqlConnection State has changed from Closed to Open Calling mySqlConnection.Close() mySqlConnection State has changed from Open to Closed The InfoMessage Event The InfoMessage event fires when the database returns a warning or information message produced by the database. You use the InfoMessage event to monitor these messages. To get the message, you read the contents of the Errors collection from the SqlInfoMessageEventArgs object. You can produce information and error messages using the SQL Server PRINT or RAISERROR statements, which are described in Chapter 4, "Introduction to Transact- SQL Programming." The following InfoMessageHandler() method is used to handle the InfoMessage event. Notice the use of the Errors collection to display the message: public static void InfoMessageHandler( object mySender, SqlInfoMessageEventArgs myEvent ) { Console.WriteLine( "The following message was produced:\n" + myEvent.Errors[0] ); }
  6. Note If you're using the OLE DB managed providers, you replace SqlInfoMessageEventArgs with OleDbInfoMessageEventArgs. If you're using the ODBC managed providers, you replace SqlInfoMessageEventArgs with OdbcInfoMessageEventArgs. Listing 7.4 illustrates the use of the InfoMessage event. You'll notice this program uses the ExecuteNonQuery() method of the SqlCommand object to send PRINT and RAISERROR statements to the database for execution. You'll learn the details of the SqlCommand object and the ExecuteNonQuery() method in Chapter 8, "Executing Database Commands." Listing 7.4: INFOMESSAGE.CS /* InfoMessage.cs illustrates how to use the InfoMessage event */ using System; using System.Data; using System.Data.SqlClient; class InfoMessage { // define the InfoMessageHandler() method to handle the // InfoMessage event public static void InfoMessageHandler( object mySender, SqlInfoMessageEventArgs myEvent ) { Console.WriteLine( "The following message was produced:\n" + myEvent.Errors[0] ); } public static void Main() { // create a SqlConnection object SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); // monitor the InfoMessage event using the InfoMessageHandler() method mySqlConnection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
  7. // open mySqlConnection mySqlConnection.Open(); // create a SqlCommand object SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); // run a PRINT statement mySqlCommand.CommandText = "PRINT 'This is the message from the PRINT statement'"; mySqlCommand.ExecuteNonQuery(); // run a RAISERROR statement mySqlCommand.CommandText = "RAISERROR('This is the message from the RAISERROR statement', 10, 1)"; mySqlCommand.ExecuteNonQuery(); // close mySqlConnection mySqlConnection.Close(); } } The output from this program is as follows: The following message was produced: System.Data.SqlClient.SqlError: This is the message from the PRINT statement The following message was produced: System.Data.SqlClient.SqlError: This is the message from the RAISERROR statement
Đồng bộ tài khoản