C# 与Sql server 获取数据和执行命令

C#数据库命封装在 System.Data.SqlClient 之中;

从使用的数据库中获取连接串connectionstring:"server=xx.xxx.xx.xx,xxxx: database=xxx:uid=xxxx:pwd=xxx;"

推荐使用using(){} 连接数据书库,再使用结束后会自动断开连接;

 1 using (SqlConnection conn = new SqlConnection(ConnectionString))
 2             {
 3 
 4                 conn.Open();
 5     
 6                //结构化查询  使用存储过程执行
 7                 SqlCommand cmd = new SqlCommand("PL_GET_Item", conn);
 8                 cmd.CommandType = CommandType.StoredProcedure;
 9           
10                 cmd.Parameters.Add("@Level", SqlDbType.Int);  //插入过程的参数
11                 cmd.Parameters["@Level"].Value = level;
12           
13                 cmd.Parameters.Add("@Title", SqlDbType.VarChar, 50);
14                 cmd.Parameters["@Title"].Value = title;
15                  
16                 SqlDataAdapter da = new SqlDataAdapter(cmd);  // 使用SqlDataAdapter
17 
18                 da.Fill(dt);
19 
20                 return dt;
21             }        

SqlConnection  用来创建与数据库的连接

  是C#对数据库操作的第一步; 使用Open();方法打开连接 Close(); 方法关闭连接;

  没有打开连接的话后续的过程将会报错;忘记关闭的话,会造成资源的浪费(我只知道这一点点QAQ)

下面是SQLConnection的构造函数

 名称说明
System_CAPS_pubmethod SqlConnection()

初始化 SqlConnection 类的新实例。

System_CAPS_pubmethod SqlConnection(String)

如果给定包含连接字符串的字符串,则初始化 SqlConnection 类的新实例。

System_CAPS_pubmethod SqlConnection(String, SqlCredential)

在给定连接字符串的情况下,初始化 SqlConnection 类的新实例,该连接字符串不使用 Integrated Security = true 和包含用户 ID 和密码的 SqlCredential 对象。

SqlCommand  表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。

构造函数

 名称说明
System_CAPS_pubmethod SqlCommand()

初始化 SqlCommand 类的新实例。

System_CAPS_pubmethod SqlCommand(String)

使用查询的文本初始化 SqlCommand 类的新实例。

System_CAPS_pubmethod SqlCommand(String, SqlConnection)

使用查询的文本和 SqlConnection 初始化 SqlCommand 类的新实例。

System_CAPS_pubmethod SqlCommand(String, SqlConnection, SqlTransaction)

使用查询文本、SqlConnection 以及 SqlTransaction 初始化 SqlCommand 类的新实例。

System_CAPS_pubmethod SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting)

使用指定的命令文本、连接、事务和加密设置初始化 SqlCommand 类的新实例。

原文地址:https://www.cnblogs.com/ILoveMyJob/p/9377501.html