执行优化和参数传递

一、SqlConnection 连接状态判断

属性:conn.State

枚举类型 ConnectionState

// 如果连接未打开,则开启连接
if (conn.State != ConnectionState.Open)
{
    conn.Open();
}Code language: JavaScript (javascript)

注意:配合 using 使用时,连接释放后状态自动变为 Closed。
常见状态:Open / Closed / Connecting 等。

二、ExecuteScalar 空值判断重点

ExecuteScalar对它的返回值进行判断,避免null值报错

object obj = sqlCom.ExecuteScalar();

// 必须同时判断 null 和 DBNull.Value
if (obj == null || obj == System.DBNull.Value)
{
    MessageBox.Show("结果为null");
}
else
{
    MessageBox.Show(obj.ToString());
}Code language: JavaScript (javascript)

区分:

  • null:没有返回任何一行数据
  • DBNull.Value:查询到行,但该字段数据库值为 NULL

三、SqlCommand 参数体系(防SQL注入核心)

1. 核心对象

SqlCommand.Parameters 集合,存放多个 SqlParameter 参数。使用参数化查询,可以彻底杜绝SQL注入漏洞。

2. 创建参数示例
// 参数名、类型、长度
SqlParameter paramSql = new SqlParameter("@Title", SqlDbType.NVarChar, 250);

// 赋值
paramSql.Value = model.Title;

// 添加到命令对象
sqlCom.Parameters.Add(paramSql);Code language: JavaScript (javascript)
3. 参数方向 ParameterDirection(枚举)
paramSql.Direction = ParameterDirection.Output;
枚举说明
Input1默认,传入参数(给SQL传值)
Output2输出参数,存储过程执行后拿回结果
InputOutput3既可传入,执行后又可输出

完整示例

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=.;Initial Catalog=db;User ID=sa;Password=xxx";
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        // 安全打开连接
        if (conn.State != ConnectionState.Open)
        {
            conn.Open();
        }

        SqlCommand sqlCom = new SqlCommand();
        sqlCom.Connection = conn;
        sqlCom.CommandTimeout = 60;
        // 参数化SQL,不要字符串拼接!
        sqlCom.CommandText = "SELECT [Title] FROM [dbo].[Article] WHERE Title = @Title";

        // 构造参数
        SqlParameter paramTitle = new SqlParameter("@Title", SqlDbType.NChar, 10);
        paramTitle.Value = "测试标题";
        sqlCom.Parameters.Add(paramTitle);

        object obj = sqlCom.ExecuteScalar();
        if (obj == null || obj == DBNull.Value)
        {
            MessageBox.Show("结果为null");
        }
        else
        {
            MessageBox.Show(obj.ToString());
        }
    }
}Code language: JavaScript (javascript)

重要开发规范

  1. 禁止字符串拼接SQL,永远使用 SqlParameter 参数化;
  2. 所有 SqlConnectionSqlCommand 优先使用 using 自动释放资源;
  3. ExecuteScalar 一定要双重判断 null + DBNull.Value
  4. 区分 CommandTimeout(SQL执行超时)和连接字符串内的 Connect Timeout(建立连接超时)。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注