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

Windows窗体连接SQL Server运行报错:INSERT语句列数与值数不匹配

问题排查与解决

核心错误原因

你的SQL语句拼接逻辑有误:VALUES子句里的三个字段值没有分别用单引号包裹,导致数据库将三个文本的拼接结果识别为单个值,但INSERT语句指定了3列,因此触发列数与值数不匹配的异常。

举个实际拼接后的错误SQL示例:

INSERT INTO [MyTable] (Name, Surename, Address) VALUES ('张三,李四,北京市')

这里VALUES仅包含1个值,与声明的3列完全不匹配。

快速修复拼接写法

给每个文本框的内容单独添加单引号,确保每个值都被正确识别:

private void button1_Click (object sender, EventArgs e)
{
    connection.Open();

    SqlCommand cmd = connection.CreateCommand();
    cmd.CommandType = CommandType.Text;
    // 为每个字段值单独添加单引号
    cmd.CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES ('"+ textBox1.Text +"','"+ textBox2.Text + "','" + textBox3.Text + "')";

    cmd.ExecuteNonQuery();
    connection.Close();

    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    textBox4.Text = "";
}

推荐:使用参数化查询避免SQL注入

直接拼接字符串的写法存在严重的SQL注入风险,比如用户输入包含单引号的内容时会直接报错,甚至被恶意利用。更安全的做法是使用参数化查询:

private void button1_Click (object sender, EventArgs e)
{
    // 使用using块自动释放资源,防止连接泄漏
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES (@Name, @Surename, @Address)";
        
        // 绑定参数
        cmd.Parameters.AddWithValue("@Name", textBox1.Text);
        cmd.Parameters.AddWithValue("@Surename", textBox2.Text);
        cmd.Parameters.AddWithValue("@Address", textBox3.Text);

        cmd.ExecuteNonQuery();
        connection.Close();
    }

    // 清空输入框
    textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
}

更规范的写法是将数据库连接也放入using块,确保连接被正确释放:

private void button1_Click (object sender, EventArgs e)
{
    // 替换为你的数据库连接字符串
    string connString = "Data Source=你的服务器;Initial Catalog=你的数据库;Integrated Security=True";
    using (var connection = new SqlConnection(connString))
    using (var cmd = connection.CreateCommand())
    {
        connection.Open();
        cmd.CommandText = "INSERT INTO [MyTable] (Name, Surename, Address) VALUES (@Name, @Surename, @Address)";
        
        cmd.Parameters.AddWithValue("@Name", textBox1.Text);
        cmd.Parameters.AddWithValue("@Surename", textBox2.Text);
        cmd.Parameters.AddWithValue("@Address", textBox3.Text);

        cmd.ExecuteNonQuery();
    }

    textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
}

额外检查点

  • 确认数据库表MyTable的列名拼写正确,比如你写的Surename是否是实际表中的Surname(拼写错误会导致列不匹配)
  • 确保输入的内容符合列的类型和约束要求,比如非空列不能传入空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:00:50