【问题标题】:There are more columns in the INSERT statement than values specified in the VALUES clause?INSERT 语句中的列多于 VALUES 子句中指定的值?
【发布时间】:2015-01-24 10:20:01
【问题描述】:

我一直在这个问题上磕磕绊绊,但无法在我的 sql insert 语句中配置错误。我需要在表中插入一个新行,但是 它一直告诉我插入语句中的列比子句中的多。

这是我的声明:

kSqlCommand.CommandText = "INSERT INTO BillsDetails ([BillID],[CallDialledID],[CallDateTime],[CallDuration],[CallNetPrice],[CallRetailPrice],[CallDiscountPrice]) VALUES ('" + strBillID + "','" + strDialledNumberID + "','" + strCallDate + "','" + strCallDuration + "','" + dCallNetPrice + "','" + dCallRetailPrice + "','" + dCallDiscountPrice + "')";//SqlStatement to Add new Bill
kSqlCommand.ExecuteReader();

每次我得到这个错误:

"INSERT 语句中的列多于指定的值 在使用 c# 的 VALUES 子句中。 VALUES 中的值的数量 子句必须与 INSERT 中指定的列数匹配 声明。”

显然,这是一个语法问题,因为 INSERT 语句中的列 = 给定值的数量。

任何帮助将不胜感激..

【问题讨论】:

  • ExecuteReader 返回数据。您需要改用ExecuteNonQuery。但是你有 7 列和 7 个值。此 sql 语句适用于 SQL Server?而且您应该始终使用参数化查询。这种字符串连接对 SQL 注入攻击开放。
  • 您连接在一起的任何字符串是否包含逗号?顺便说一句,你是广泛开放的 SQL 注入。

标签: c# mysql sql-server


【解决方案1】:
string cmdString="INSERT INTO BillsDetails('BillID','CallDialledID','CallDateTime','CallDuration','CallNetPrice','CallRetailPrice','CallDiscountPrice') VALUES (@val1, @va2, @val3,@val4, @va5, @val6,@val7)";
string connString = "your connection string";
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandString = cmdString;
        comm.Parameters.AddWithValue("@val1", 'your value');
        comm.Parameters.AddWithValue("@val2", 'your value');
        comm.Parameters.AddWithValue("@val3", 'your value');
        comm.Parameters.AddWithValue("@val4", 'your value');
        comm.Parameters.AddWithValue("@val5", 'your value');
        comm.Parameters.AddWithValue("@val6", 'your value');
        comm.Parameters.AddWithValue("@val7", 'your value');
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
        }
        Catch(SqlException e)
        {

        }
    }
}

我想尝试使用 ExecuteNonQuery 而不是 ExecuteReader 因为 ExecuteReader 正在读取数据库内容而不是插入行 请阅读这篇文章https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx,.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多