c# dbconnection
时间: 2023-07-27 22:26:26 浏览: 58
C#中的DBConnection是一个抽象类,它表示与数据库的连接。DBConnection类是所有特定数据库连接类(如SqlConnection、OleDbConnection等)的基类。使用DBConnection可以打开连接、执行命令和关闭连接。以下是一个使用DBConnection的示例代码:
```
using System.Data.Common;
using System.Data.SqlClient;
DbConnection connection = new SqlConnection("Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password");
connection.Open();
DbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM MyTable";
DbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理结果集
}
reader.Close();
connection.Close();
```
在这个示例中,我们使用SqlConnection类创建一个与SQL Server数据库的连接。然后,我们打开连接并执行一个简单的SELECT查询。最后,我们使用DbDataReader类处理查询结果,并在完成后关闭连接。