错误:System.Data.OleDb.OleDbException(0x80040E14):查询表达式中的语法错误(缺少运算符)

时间:2019-04-02 15:39:25

标签: c#

我正在尝试将存储过程的结果导出到Excel,并在运行时收到以下错误:System.Data.OleDb.OleDbException(0x80040E14):查询表达式中的语法错误(缺少运算符)。下面是我正在使用的代码。创建了excel文件,但没有数据填充该文件。

string TableColumns = "";

// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
    foreach (DataColumn column in table.Columns)
    {
        TableColumns += column + "],[";
    }
}

// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();

//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
    String sqlCommandInsert = "";
    String sqlCommandValue = "";
    foreach (DataColumn dataColumn in table.Columns)
    {
        sqlCommandValue += dataColumn + "],[";
    }

    sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
    sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
    sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue + ") VALUES(";

    int columnCount = table.Columns.Count;
    foreach (DataRow row in table.Rows)
    {
        string columnvalues = "";
        for (int i = 0; i < columnCount; i++)
        {
            int index = table.Rows.IndexOf(row);
            columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
        }
        columnvalues = columnvalues.TrimEnd(',');
        var command = sqlCommandInsert + columnvalues + ")";
        Excel_OLE_Cmd.CommandText = command;
        Excel_OLE_Cmd.ExecuteNonQuery();
    }
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;

1 个答案:

答案 0 :(得分:1)

因此,此问题与您的数据中有未转义的单引号有关。处理该问题的两种选择是转义单引号(将其转换为两个单引号):

  $(".typedsmartbackspace").typed({
         strings: ['Dog', 'Cat', 'Mouse', 'Hamster'],
         typeSpeed: 80,
         backSpeed: 20,
         startDelay: 1000,
         backDelay: 300,
         loop: true,
         showCursor: true,
  });

或另一个选择(也是更可靠的选择)是使用参数化查询。我将只使用代码的下半部分来执行此查询的建立和插入,并向您展示如何做到这一点(以及一些清理工作并使用['Dog', 'Cat', 'Mouse', 'Hamster'])。请注意,由于没有可用的测试数据,因此我没有进行编译和测试。

string myData = "This string won't work";
string myDataEscaped = myData.Replace("'", "''");