如何将参数添加到OleDbDataReader

时间:2011-12-05 11:45:46

标签: c# asp.net ado.net

当我尝试使用ADO.NET写入excel文件时出现语法错误。如何向查询添加参数。我正在更新一个mysql数据库。

string error="Text for status";
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";

System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection(connectionString);
string ExcelQuery;

ExcelQuery = "Update [Sheet1$] set Status="+error; // from Sheet1";

//Create the command to be executed
ExcelCommand = new System.Data.OleDb.OleDbCommand(ExcelQuery, ExcelConnection);

//Open the connection to the file
ExcelConnection.Open();

//Execute the update
ExcelCommand.ExecuteNonQuery();

//Close the connection
ExcelConnection.Close();
  

查询表达式中的语法错误(缺少运算符)'的文本   状态。

2 个答案:

答案 0 :(得分:0)

您的'声明中似乎缺少UPDATE

ExcelQuery = "Update [Sheet1$] set [Status]='" + error + "'";

答案 1 :(得分:0)

您可以使用OleDbCommand.Parameters.Add向命令添加参数。

public void CreateMyOleDbCommand(OleDbConnection connection,
    string queryString, OleDbParameter[] parameters) 
{
    OleDbCommand command = new OleDbCommand(queryString, connection);
    command.CommandText = 
        "SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
    command.Parameters.Add(parameters);

    for (int j=0; j<parameters.Length; j++)
    {
        command.Parameters.Add(parameters[j]) ;
    }

    string message = "";
    for (int i = 0; i < command.Parameters.Count; i++) 
    {
        message += command.Parameters[i].ToString() + "\n";
    }
    MessageBox.Show(message);
}