public static void WriteData(string colName,string data)
{
using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Constants.FileName + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=3;READONLY=FALSE\""))
{
// string query = String.Format("INSERT INTO [DataSet$]({0}) VALUES ({1})",colName, data);
string query = String.Format("INSERT INTO [DataSet$]({0}) VALUES ({1})", colName, data);
cn.Open();
OleDbCommand cmd = new OleDbCommand(query, cn);
cmd.Parameters.AddWithValue("@colName", colName);
cmd.Parameters.AddWithValue("@data", data);
cmd.ExecuteNonQuery();
cn.Close();
cn.Dispose();
}
}
答案 0 :(得分:0)
您要做的是混合动态查询生成和查询参数。 您不能使用命令参数来填充查询中的列名称。参数仅用于将值传递给查询。
所以你需要做的是,只使用string.Format
在查询中放置列名,并仅使用命令参数将数据传递给查询。
public void WriteData(string colName, string data)
{
using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Constants.FileName + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=3;READONLY=FALSE\""))
{
string query = string.Format("INSERT INTO [DataSet$] ({0}) VALUES (@data)", colName);
// The query variable will have following value assuming colName=token
//INSERT INTO [DataSet$] (token) VALUES (@data)
cn.Open();
//Now use OleDbCommand to pass value of @data to the query.
OleDbCommand cmd = new OleDbCommand(query, cn);
cmd.Parameters.AddWithValue("@data", data);
cmd.ExecuteNonQuery();
cn.Close();
}
}
这可以帮助您解决问题。
答案 1 :(得分:0)
public static void UpdateData(string keyName,string colName,string data)
{
using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Constants.FileName + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=3;READONLY=FALSE\""))
{
// string query = String.Format("INSERT INTO [DataSet$]({0}) VALUES ({1})",colName, data);
connection.Open();
string commandString = String.Format("UPDATE [DataSet$] SET colName ='{0}' WHERE keyName = '{1}'",@data,@keyName);
OleDbCommand cmd = new OleDbCommand(commandString, connection);
cmd.Parameters.AddWithValue("@data", data);
cmd.Parameters.AddWithValue("@keyName", keyName);
connection.Close();
connection.Dispose();
}
}
}