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

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

0
105
lượt xem
18
download

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

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

Using a SqlConnection Object to Connect to a SQL Server Database You create a SqlConnection object using the SqlConnection() constructor. This constructor is overloaded

Chủ đề:
Lưu

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

  1. Using a SqlConnection Object to Connect to a SQL Server Database You create a SqlConnection object using 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 SqlConnection object using 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 SQL Server 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 =
  2. "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 to SQL Server and use those credentials to connect to the database. This saves you from providing a separate username and password to SQL 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 to SQL Server. SQL Server 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 SQL Server Books Online documentation.) You've now seen how to create a Connection object using program statements. You'll see how to create a Connection object visually using Visual Studio .NET later in the
  3. "Creating a Connection Object using Visual Studio .NET" section. Next, you'll see how to open and close a connection. Opening and Closing a Database 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 to connect to the SQL Server Northwind database using a SqlConnection object and display some of the properties of that object. Listing 7.1: MYSQLCONNECTION.CS /* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server database */ 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 a SqlConnection object to connect to the // database, passing the connection string to the constructor SqlConnection mySqlConnection =
  4. new SqlConnection(connectionString); // open the database connection using the // Open() method of the SqlConnection object mySqlConnection.Open(); // display the properties of the SqlConnection object 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 SqlConnection object 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
  5. workstation ID will be different. Connection Pooling Opening and closing a database 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 database to 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 using a SqlConnection 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 SqlConnection object and the pool is already full with currently used objects, your request waits until a SqlConnection object 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 */
  6. using System; using System.Data; using System.Data.SqlClient; class ConnectionPooling { public static void Main() { // create a SqlConnection object to connect to 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 SqlConnection object 10 times for (int count = 1; count
  7. mySqlConnection.Close(); } } }
Đồng bộ tài khoản