private SqlConnection sqlConnection1 = null;
时间: 2024-05-13 08:15:39 浏览: 20
这是在 C# 中用于连接与操作 SQL Server 数据库的对象。SqlConnection 对象表示与 SQL Server 数据库的打开连接,它提供了访问和操作 SQL Server 数据库的方法和属性。一般情况下,我们需要先创建一个 SqlConnection 对象,然后通过它提供的 Open() 方法打开数据库连接,最后通过 SqlCommand 对象执行 SQL 语句。在使用完毕后,需要显式地调用 Close() 方法关闭数据库连接,以释放资源。以下是一个简单的使用示例:
```
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM myTable";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0), reader.GetString(1));
}
reader.Close();
sqlConnection1.Close();
Console.ReadKey();
}
}
```
在上述示例中,我们首先创建了一个字符串类型的 connectionString 对象,它包含了连接 SQL Server 数据库所需要的信息。然后通过这个字符串创建了一个 SqlConnection 对象,并设置了需要执行的 SQL 语句。接下来,我们通过 SqlConnection 对象的 Open() 方法打开数据库连接,并通过 SqlCommand 对象的 ExecuteReader() 方法执行 SQL 语句,并获取查询结果。最后,通过 SqlDataReader 对象的 Read() 方法遍历查询结果,最后显式地关闭 SqlDataReader 和 SqlConnection 对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)