You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLite参数未替换引发‘参数不足’错误,求排查

SQLite参数插入失败问题排查与解决

问题情况

创建SQLite 3数据库,包含TestTable表(两列:ID int自增、UserInput TEXT),尝试将文本框用户输入插入数据库时,发现CommandText中的@paramInput占位符未被替换(实际这是参数化查询的正常表现),使用Parameters.AddWithValue和Parameters.Add两种方式添加参数后,执行均提示“Insufficient parameters supplied”错误,使用的是System.Data.SQLite.Core 1.0.116版本。

原代码如下:

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        string strValue = editBox1.Text;
        SQLiteCommand cmd = cnn.CreateCommand();
        cmd.CommandText = "insert into main.TestTable (UserInput) values (@paramInput)";

        //replace @paramInput by using AddWithValue
        cmd.Parameters.AddWithValue("@paramInput", strValue);

        //check result before 
        MessageBox.Show(cmd.CommandText);
        
        //write to DB
        cnn.Execute(cmd.CommandText);
    }
}

也曾尝试的参数添加方式:

//replace @paramInput by using Add
cmd.Parameters.Add("@paramInput", DbType.String);
cmd.Parameters[0].Value = strValue;

问题原因与修复

核心错误

你调用的cnn.Execute(cmd.CommandText)只是直接执行了原始SQL字符串,并未关联已配置好参数的SQLiteCommand对象。参数化查询的占位符不会直接替换到CommandText中(这是防止SQL注入的安全机制),所以MessageBox.Show(cmd.CommandText)看到占位符是正常现象,但直接执行带占位符的SQL会导致参数不足错误。

修复后的代码

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        string strValue = editBox1.Text;
        SQLiteCommand cmd = cnn.CreateCommand();
        cmd.CommandText = "insert into main.TestTable (UserInput) values (@paramInput)";

        // 使用AddWithValue添加参数(两种方式都可以,选一种即可)
        cmd.Parameters.AddWithValue("@paramInput", strValue);
        // 或使用Add方式:
        // cmd.Parameters.Add("@paramInput", DbType.String);
        // cmd.Parameters[0].Value = strValue;

        // 显式打开连接(规范操作)
        cnn.Open();
        // 调用SQLiteCommand的ExecuteNonQuery执行插入
        cmd.ExecuteNonQuery();
    }
}

关键要点

  • 不要直接执行SQL字符串,要使用配置好参数的SQLiteCommand对象调用ExecuteNonQuery()方法。
  • 参数化查询的占位符不会被替换到CommandText中,这是正常的安全设计,无需纠结。
  • 执行命令前显式调用cnn.Open(),避免依赖自动打开的隐式行为,代码更清晰可靠。

内容的提问来源于stack exchange,提问作者Pete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:31:03