Using aSqlConnectionObjecttoConnecttoaSQLServerDatabase You create aSqlConnectionobjectusing the SqlConnection() constructoction object toconnecttoasqlserverdatabasephần 2' title='using asqlconnectionobjecttoconnecttoasqlserverdatabasephần 2'>Using aSqlConnectionObjecttoConnecttoaSQLServerDatabase You create aSqlConnectionobjectusing the SqlConnection() constructor. This constructor is overloaded, meaning that there are multiple versions of the constructor that you can call. The SqlConnection() constructors are as follows: SqlConnection() SqlConnection(string connectionString) where connectionString contains the details for the database connection. You'll learn the details of the connectionString in this section. Assuming you've imported the System.Data.SqlClient namespace, you can create a new SqlConnectionobjectusing the following statement: SqlConnection mySqlConnection = new SqlConnection(); You can then set the details for the database connection using the ConnectionString property of mySqlConnection. For example: mySqlConnection.ConnectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; where server specifies the name of the computer on which SQLServer is running. database specifies the name of the database. uid specifies the name of the database user. pwd specifies the password for the user. Warning For security reasons, do not include the username password in your production code. Instead ask the user to enter their name and password-or use integrated security, which you'll learn about shortly. One thing you need to bear in mind is that you can set the ConnectionString property only when your Connection object is closed. You can also pass a connection string directly to the SqlConnection() constructor. For example: string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; SqlConnection mySqlConnection = new SqlConnection(connectionString); Or more simply: SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" ); You can set an optional connection timeout, which specifies the number of seconds that the Open() method will wait for a connection to the database. You do this by specifying a connection timeout in your connection string. For example, the following string specifies a connection timeout of 10 seconds: string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa;" + "connection timeout=10"; Note The default connection timeout is 15 seconds. A connection timeout of 0 seconds means the connection attempt will wait indefinitely. Avoid setting your connection timeout to 0. Before starting a Windows session, you typically log in to Windows with a username and password. If you're using Windows integrated security, you can pass your username and password toSQLServer and use those credentials toconnectto the database. This saves you from providing a separate username and password toSQL Server. You can use integrated security in your program by specifying integrated security=SSPI in your connection string. For example: string connectionString = "server=localhost;database=Northwind;integrated security=SSPI"; Notice that you don't provide the username and password. Instead, the username and password you used when logging into Windows is passed toSQL Server. SQLServer will then check its list of users to see if you have permission to access the database. (For further details on integrated security, consult the SQLServer Books Online documentation.) You've now seen how to create a Connection objectusing program statements. You'll see how to create a Connection object visually using Visual Studio .NET later in the "Creating a Connection Objectusing Visual Studio .NET" section. Next, you'll see how to open and close a connection. Opening and Closing aDatabase Connection Once you've created your Connection object and set its ConnectionString property to the appropriate details for your database connection, you can open the connection to the database. You do this by calling the Open() method of your Connection object. The following example calls the Open() method of mySqlConnection: mySqlConnection.Open(); Once you've finished with your database connection, you call the Close() method of your Connection object. For example: mySqlConnection.Close(); Listing 7.1 illustrates how toconnectto the SQLServer Northwind databaseusingaSqlConnectionobject and display some of the properties of that object. Listing 7.1: MYSQLCONNECTION.CS /* MySqlConnection.cs illustrates how to use a SqlConnectionobjecttoconnecttoaSQLServerdatabase */ using System; using System.Data; using System.Data.SqlClient; class MySqlConnection { public static void Main() { // formulate a string containing the details of the // database connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa"; // create aSqlConnectionobjecttoconnectto the // database, passing the connection string to the constructor SqlConnection mySqlConnection = new SqlConnection(connectionString); // open the database connection using the // Open() method of the SqlConnectionobject mySqlConnection.Open(); // display the properties of the SqlConnectionobject Console.WriteLine("mySqlConnection.ConnectionString = "+ mySqlConnection.ConnectionString); Console.WriteLine("mySqlConnection.ConnectionTimeout = "+ mySqlConnection.ConnectionTimeout); Console.WriteLine("mySqlConnection.Database = "+ mySqlConnection.Database); Console.WriteLine("mySqlConnection.DataSource = "+ mySqlConnection.DataSource); Console.WriteLine("mySqlConnection.PacketSize = "+ mySqlConnection.PacketSize); Console.WriteLine("mySqlConnection.ServerVersion = "+ mySqlConnection.ServerVersion); Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State); Console.WriteLine("mySqlConnection.WorkstationId = "+ mySqlConnection.WorkstationId); // close the database connection using the Close() method // of the SqlConnectionobject mySqlConnection.Close(); } } The output from this program is as follows: mySqlConnection.ConnectionString = server=localhost;database=Northwind;uid=sa; mySqlConnection.ConnectionTimeout = 15 mySqlConnection.Database = Northwind mySqlConnection.DataSource = localhost mySqlConnection.PacketSize = 8192 mySqlConnection.ServerVersion = 08.00.0194 mySqlConnection.State = Open mySqlConnection.WorkstationId = JMPRICE-DT1 Note Your results will differ from those here. For example, your connection string and workstation ID will be different. Connection Pooling Opening and closing adatabase connection is a relatively time-consuming process. For this reason, ADO.NET automatically stores database connections in a pool. Connection pooling offers a great performance improvement because you don't have to wait for a brand new connection to the databaseto be established when there's a suitable connection already available. When you close a connection, that connection isn't actually closed; instead, your connection is marked as unused and stored in the pool, ready to be used again. If you then supply the same details in the connection string (same database, username, password, and so on), then the connection from the pool is retrieved and returned to you. You then use that same connection to access the database. When usingaSqlConnection object, you can indicate the maximum number of connections allowed in the pool by specifying max pool size in your connection string (the default is 100). You can also indicate the minimum number of connections in the pool by specifying min pool size (the default is 0). For example, the following SqlConnection specifies a max pool size of 10 and a min pool size of 5: SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5" ); In this example, a pool with five initial SqlConnection objects is created. A maximum of 10 SqlConnection objects can be stored in the pool. If you attempt to open a new SqlConnectionobject and the pool is already full with currently used objects, your request waits until aSqlConnectionobject is closed, at which point that object is returned for you to use. If your request waits longer than the number of seconds in the ConnectionTimout property, then an exception is thrown. Listing 7.2 illustrates the time-saving when opening a previously pooled connection. Listing 7.2: CONNECTIONPOOLING.CS /* ConnectionPooling.cs illustrates connection pooling */ using System; using System.Data; using System.Data.SqlClient; class ConnectionPooling { public static void Main() { // create aSqlConnectionobjecttoconnectto the database, // setting max pool size to 10 and min pool size to 5 SqlConnection mySqlConnection = new SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5" ); // open the SqlConnectionobject 10 times for (int count = 1; count <= 10; count++) { Console.WriteLine("count = "+ count); // create a DateTime object and set it to the // current date and time DateTime start = DateTime.Now; // open the database connection using the // Open() method of the SqlConnectionobject mySqlConnection.Open(); // subtract the current date and time from the start, // storing the difference in a TimeSpan TimeSpan timeTaken = DateTime.Now - start; // display the number of milliseconds taken to open // the connection Console.WriteLine("Milliseconds = "+ timeTaken.Milliseconds); // display the connection state Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State); // close the database connection using the Close() method // of the SqlConnectionobject mySqlConnection.Close(); } } } . Using a SqlConnection Object to Connect to a SQL Server Database You create a SqlConnection object using the SqlConnection( ) constructor. This. " ;server= localhost ;database= Northwind;uid=sa;pwd=sa"; // create a SqlConnection object to connect to the // database, passing the connection string to the constructor SqlConnection mySqlConnection