【笔记】dotnet操作MSSQL数据库

前言

dotnet操作MSSQL数据库

建立连接

  • 需要下载依赖System.Data.SqlClient

Server=127.0.0.1:定义服务器IP地址或域名
Database=<database_name>:定义数据库名称
UID=sa:定义用户名
Password=<password>:定义密码

1
2
3
string dsn = "Server=127.0.0.1;Database=<database_name>;UID=sa;Password=<password>;";
SqlConnection conn = new SqlConnection(dsn);
conn.Open();

利用连接对象创建命令对象

<tsql>:tsql语句

1
SqlCommand cmd = new SqlCommand("<tsql>", conn);

利用命令对象创建适配器对象

1
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

创建一个数据池

  • 用于存放从数据库中获取的数据
1
DataSet ds = new DataSet();

利用适配器填充数据池

1
adapter.Fill(ds);

从数据池中获取一个数据

1
DataTable dt = ds.Tables[0];

关闭连接并销毁

1
2
conn.Close();
conn.Dispose();

自动销毁

  • 因为SqlConnection继承自IDisposable接口,所以可以使用using关键字自动销毁
1
2
3
4
5
6
7
8
string dsn = "Server=127.0.0.1;Database=<database_name>;UID=sa;Password=<password>;";
using(SqlConnection conn = new SqlConnection(dsn))
{
conn.Open();

...

}

完成

参考文献

哔哩哔哩——全栈ACE