public class SqlHelper
{
/// <summary>
/// 连接字符串
/// </summary>
private static readonly string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
/// <summary>
/// 增、删、改的通用方法
/// 执行Sql语句或存储过程,返回受影响的行数
/// SQL注入
/// </summary>
/// <param name="sql">sql语句或存储过程名</param>
/// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public static int ExecuteNonQuery(string sql, int cmdType, params SqlParameter[] parameters)
{
//select @@Identity 返回上一次插入记录时自动产生的ID
int result = 0;//返回结果
using (SqlConnection conn = new SqlConnection(connStr))
{
//执行脚本的对象cmd
SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters);
result = cmd.ExecuteNonQuery();//执行T-SQL并返回受影响行数
cmd.Parameters.Clear();
}
//using原理:类似于try finally
return result;
}
/// <summary>
/// 执行sql查询,返回第一行第一列的值
/// </summary>
/// <param name="sql">sql语句或存储过程</param>
/// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param>
/// <param name="parameters">参数列表</param>
/// <returns></returns>
public static object ExecuteScalar(string sql, int cmdType, params SqlParameter[] parameters)
{
object result = null;//返回结果
using (SqlConnection conn = new SqlConnection(connStr))
{
//执行脚本的对象cmd
SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters);
result = cmd.ExecuteScalar();//执行T-SQL并返回第一行第一列的值
cmd.Parameters.Clear();
if (result == null || result == DBNull.Value)
{
return null;
}
else
{
return result;
}
}
}
/// <summary>
/// 执行sql查询,返回SqlDataReader对象
/// </summary>
/// <param name="sql">sql语句或存储过程</param>
/// <param name="cmdType&
11-01
174
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-25
289
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-21
166
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-10
402
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-09
353
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-08
259
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-04
217
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-03
172
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)