我目前正在使用OleDB访问数据库,我遇到了OleDBParameter的字符串替换问题。
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM " + tablename + " WHERE ID = @ID ;";
cmd.Parameters.AddWithValue("@ID", testslist.number + "_" + testcase.name + "_" + testcase.config);
OleDbDataReader reader = cmd.ExecuteReader();
RecordExists = reader.HasRows;
reader.Close();
if (RecordExists)
{
string updatestring = null;
foreach (KeyValuePair<string, string> kv in dictionary)
updatestring = updatestring + kv.Key + " = '@val" + kv.Key + "',";
cmd.CommandText = "UPDATE " + tablename + " SET " + updatestring.Remove(updatestring.Length - 1) + " WHERE ID = @ID;";
foreach(KeyValuePair<string,string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("@val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("@val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
else
{
string insertstring = "ID,";
string valuestring = "@ID,";
foreach(KeyValuePair<string,string>kv in dictionary)
{
insertstring = insertstring + kv.Key + ",";
valuestring = valuestring + "@var" + kv.Key + ",";
// valuestring = valuestring + "'"+ kv.Value+ "',";
}
cmd.CommandText = "INSERT INTO " + tablename + " (" + insertstring.Remove(insertstring.Length - 1) + ") VALUES(" + valuestring.Remove(valuestring.Length - 1) + ");";
foreach (KeyValuePair<string, string> kv in dictionary)
{
if (kv.Value == null)
cmd.Parameters.AddWithValue("@val" + kv.Key, DBNull.Value);
else
cmd.Parameters.AddWithValue("@val" + kv.Key, kv.Value);
}
cmd.ExecuteNonQuery();
}
无论出于何种原因,只有@ID在我的数据库中被正确替换。运行代码后,在我的数据库中正确替换ID,但每个其他字段值都是@var [nameofthekey](例如@varTestCase)。我真的不知道在哪里看,特别是因为一个参数在数据库中被正确替换,而不是另一个。
感谢您的帮助!
编辑:我忘了提及,我正在使用访问数据库(accdb)