2011-12-05 72 views
0

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

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(); 

语法错误(缺少操作员)在查询表达式 '文字的 状态'。

+0

我正在使用字符串错误更新excel中的状态列。应该向它添加参数还是可以不使用参数执行 – Murthy

回答

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); 
} 
+0

我正在做更新,我可以用它来做更新查询 – Murthy

+0

为“Update”或“Select”或“Ins​​ert”添加参数到oleDbCommand是相同的。 –

0

看起来像是您的UPDATE声明中缺少'

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

+0

执行更改后出现同样的错误查询表达式'' – Murthy

+0

中的语法错误(缺少运算符)'Status'字段的格式是什么? –