SqlConnection using
时间: 2023-08-22 10:05:51 浏览: 46
SqlConnection是.NET Framework中用于连接到SQL Server数据库的类。它允许您打开数据库连接,执行SQL命令并访问返回的数据。以下是使用SqlConnection的基本示例:
```
using System.Data.SqlClient;
// 创建数据库连接字符串
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
// 创建SqlConnection对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开数据库连接
connection.Open();
// 执行SQL命令
SqlCommand command = new SqlCommand("SELECT * FROM myTable", connection);
SqlDataReader reader = command.ExecuteReader();
// 处理返回的数据
while (reader.Read())
{
Console.WriteLine(reader["columnName"]);
}
// 关闭SqlDataReader和SqlConnection对象
reader.Close();
connection.Close();
}
```
在上面的示例中,我们使用SqlConnection连接到SQL Server数据库,并执行一个简单的SELECT语句。SqlCommand对象用于执行SQL命令,并返回SqlDataReader对象,该对象用于访问返回的数据。最后,我们关闭SqlDataReader和SqlConnection对象,以释放资源并关闭数据库连接。