Csharp/CSharp Tutorial/ADO.Net/SqlConnection Event
how to use the InfoMessage event
<source lang="csharp">using System; using System.Data; using System.Data.SqlClient; class InfoMessage {
public static void InfoMessageHandler(object mySender, SqlInfoMessageEventArgs myEvent) { Console.WriteLine("The following message was produced:\n" + myEvent.Errors[0]); } public static void Main() { SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); mySqlConnection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler); mySqlConnection.Open(); SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.rumandText = "PRINT "This is the message from the PRINT statement""; mySqlCommand.ExecuteNonQuery(); mySqlCommand.rumandText = "RAISERROR("This is the message from the RAISERROR statement", 10, 1)"; mySqlCommand.ExecuteNonQuery(); mySqlConnection.Close(); }
}</source>
Listen to Connection state changed event
<source lang="csharp">using System; using System.Data; using System.Data.SqlClient;
class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);Integrated security=SSPI;Initial Catalog=AdventureWorks;"; SqlConnection connection = new SqlConnection( ); connection.StateChange += new StateChangeEventHandler(connection_StateChange); connection.ConnectionString = sqlConnectString + "Connection Timeout=15;Connection Lifetime=0;" + "Min Pool Size=0;Max Pool Size=100;Pooling=true;"; Console.WriteLine("Connection string = {0}",connection.ConnectionString); connection.Open(); connection.Close(); connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection Lifetime=0;" + "Min Pool Size=0;Max Pool Size=200;Pooling=true;"; Console.WriteLine("\nConnection string = {0}",connection.ConnectionString); connection.Open(); connection.Close(); } static void connection_StateChange(object sender, StateChangeEventArgs e) { Console.WriteLine("\tOriginalState = {0}", e.OriginalState.ToString()); Console.WriteLine("\tCurrentState = {0}", e.CurrentState.ToString()); } }</source>
Using ADO.NET Events
<source lang="csharp">using System; using System.Data; using System.Data.SqlClient; class MainClass {
static void Main(string[] args) { SqlConnection MyConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;"); MyConnection.StateChange += new StateChangeEventHandler(OnStateChange); MyConnection.Open(); //Trigger Open Event MyConnection.Close(); } public static void OnStateChange(object sender, System.Data.StateChangeEventArgs e) { Console.WriteLine("Connection State Chnaged: {0}", ((SqlConnection)sender).State); }
}</source>
Connection State Chnaged: Open Connection State Chnaged: Closed