Microsoft.Data.SqlClient使用例子
时间: 2024-05-02 09:18:58 浏览: 144
以下是Microsoft.Data.SqlClient的使用示例:
1. 连接到数据库
```c#
using Microsoft.Data.SqlClient;
//定义连接字符串
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
//创建连接对象
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.GetString(0));
}
//关闭连接
reader.Close();
}
```
2. 参数化查询
```c#
using Microsoft.Data.SqlClient;
//定义连接字符串
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
//创建连接对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
//打开连接
connection.Open();
//定义SQL语句和参数
string sql = "SELECT * FROM myTable WHERE Id = @Id";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@Id", 1);
//执行SQL语句
SqlDataReader reader = command.ExecuteReader();
//输出结果
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
//关闭连接
reader.Close();
}
```
3. 执行存储过程
```c#
using Microsoft.Data.SqlClient;
//定义连接字符串
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
//创建连接对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
//打开连接
connection.Open();
//创建命令对象
SqlCommand command = new SqlCommand("myStoredProcedure", connection);
command.CommandType = CommandType.StoredProcedure;
//添加参数
command.Parameters.AddWithValue("@param1", "value1");
command.Parameters.AddWithValue("@param2", "value2");
//执行命令
command.ExecuteNonQuery();
//关闭连接
connection.Close();
}
```
阅读全文