【问题标题】:Syntax error in INSERT INTO statementINSERT INTO 语句中的语法错误
【发布时间】:2010-12-22 18:42:25
【问题描述】:

我编写了一个连接到 MS Access 的程序。当我填写字段并向 Access 添加新项目时,程序失败。例外是“INSERT INTO 语句中的语法错误”

这里是相关代码。

****************************************************************
AdoHelper.cs
****************************************************************

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace Yad2
{
    class AdoHelper
    {
        //get the connection string from the app.config file
        //Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Yad2.accdb
        static string connectionString = Properties.Settings.Default.DBConnection.ToString();

        //declare the db connection
        static OleDbConnection con = new OleDbConnection(connectionString);

        /// <summary>
        /// To Execute queries which returns result set (table / relation)
        /// </summary>
        /// <param name="query">the query string</param>
        /// <returns></returns>
        public static DataTable ExecuteDataTable(string query)
        {

            try
            {
                con.Open();
                OleDbCommand command = new OleDbCommand(query, con);
                System.Data.OleDb.OleDbDataAdapter tableAdapter = new System.Data.OleDb.OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                tableAdapter.Fill(dt);
                return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

    /// <summary>
    /// To Execute update / insert / delete queries
    /// </summary>
    /// <param name="query">the query string</param>
    public static void ExecuteNonQuery(string query)
    {
        try
        {
            con.Open();
            System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(query, con);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

    /// <summary>
    /// To Execute queries which return scalar value
    /// </summary>
    /// <param name="query">the query string</param>
    public static object ExecuteScalar(string query)
    {
        try
        {
            con.Open();
            System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(query, con);  /// here is the Excaption !!!!!!!!!
            return command.ExecuteScalar();
        }
        catch
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

}
}

****************************************************************************


****************************************************************************
DataQueries.cs
****************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Yad2
{
    class DataQueries
    {

        public static DataTable GetAllItems()
        {
            try
            {
                string query = "Select * from Messages";

                DataTable dt = AdoHelper.ExecuteDataTable(query);

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void AddNewItem(string mesNumber, string title , string mesDate , string contactMail , string mesType , string Details )
        {
            string query = "Insert into Messages values(" + mesNumber + " , '" + title + "' , '" + mesDate + "' , '" + contactMail + "' , , '" + mesType + "' , '" + Details + "')";
            AdoHelper.ExecuteNonQuery(query);
       }

        public static void DeleteDept(int mesNumber)
        {
            string query = "Delete from Item where MessageNumber=" + mesNumber;
            AdoHelper.ExecuteNonQuery(query);
        }
    }
}
***********************************************************************************************

程序为什么会失败?

【问题讨论】:

  • "porgram"? “访问”? “例外”?您应该使用拼写检查器。
  • @abelenky:对某些人来说,英语很困难。因此,我们可以使用编辑按钮来帮助清理它。
  • @Chris:ESL 作者尤其应该使用拼写检查器。计算机会做拼写,所以我们不必这样做。

标签: c# sql


【解决方案1】:

当您将字符串放入 SQL 时,您会得到一个无效的语法。
如果其中一个字符串包含',就会发生这种情况。

你需要使用参数。

另外,您的 SQL 包含 , ,,这是无效的语法。

【讨论】:

    【解决方案2】:

    试试这个

    INSERT INTO table (column1, column2, ...)
    VALUES ('value1', 'value2', ...)
    

    【讨论】:

    • +1 我怀疑这是主要问题。在进行插入时,应显式定义所有列。否则当 DDL 更改发生时它很脆弱并且可能会爆炸。
    【解决方案3】:
    string query = "Insert into Messages values(" + mesNumber + " , '" + title + "' , '" + mesDate + "' , '" + contactMail + "' , , '" + mesType + "' , '" + Details + "')";
    

    产量

    Insert into Messages
    values(
        <number> , 
        '<title>' , 
        '<mesDate>' , 
        '<contactMail>' , , 
        '<mesType>' , 
        '<Details>'
    )
    

    注意后面的两个逗号,它们之间有一个空格。这不是有效的 SQL。如果mesNumber 在您的代码中为空值,您也会遇到错误的查询。

    正如 Joe White 在他的 XKCD #327 链接中评论的那样,始终清理您的数据库输入!这意味着如果将字符串传递给您的方法,则必须转义所有单引号。

    正如 SLaks 所说,从不使用throw ex;,只使用throw;

    【讨论】:

    • 否;只需完全删除 catch 块。
    • 你说得对,SLaks,我从来没有意识到我们可以忽略catch 块。对于那些感兴趣的人,微软是这样说的:“try 语句有三种可能的形式:一个 try 块后面跟着一个或多个 catch 块。一个 try 块后面跟着一个 finally 块。 A try 块后跟一个或多个 catch 块,然后是 finally 块。”来源:msdn.microsoft.com/en-us/library/aa664733(v=vs.71).aspx
    【解决方案4】:

    您为什么不简单地在AddNewItem 中打印出query 的值(到调试窗口、控制台、消息框、日志文件……任何地方!),然后检查消息。到时候真的应该很清楚了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      相关资源
      最近更新 更多