起初我试过这个:
string set = "";
for (int i = 1; i < result.Count; i++)
{
if ((fieldtypes[i] == "System.Int32"))
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.String")
{
set += fields[i] + "='" + result[i] + "', ";
}
else if (fieldtypes[i] == "System.Boolean")
{
set += fields[i] + "=" + result[i] + ", ";
}
else if (fieldtypes[i] == "System.DateTime")
{
set += fields[i] + "='#" + System.DateTime.Now + "#', ";
}
}
set = set.Substring(0, set.Length - 2);
string sql11 = "UPDATE [Contacts] SET " + set + " WHERE pkContactID=" + cKey;
OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection);
myCommand11.ExecuteNonQuery();
现在,当我省略了字符串和日期时间条件以便它只更新 int 和 boolean 时,这可以工作。因此,当我尝试更新类型为字符串的字段时,它与语法错误有关。
然后我听说写入.mdb文件时必须使用参数,所以我尝试了这个:
string sql11 = "UPDATE [Contacts] SET ";
for (int i = 1; i < result.Count; i++)
{
sql11 += fields[i] + " = ?, ";
}
sql11 = sql11.Substring(0, sql11.Length - 2);
sql11 += " WHERE pkContactID = " + cKey;
using (myConnection)
{
using (OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection))
{
myCommand11.CommandType = CommandType.Text;
for (int j = 1; j < result.Count; j++)
{
if (fieldtypes[j] == "System.Int32")
{
myCommand11.Parameters.AddWithValue(fields[j], int.Parse(result[j]));
}
else if (fieldtypes[j] == "System.String")
{
myCommand11.Parameters.AddWithValue(fields[j], result[j]);
}
else if (fieldtypes[j] == "System.Boolean")
{
myCommand11.Parameters.AddWithValue(fields[j], Boolean.Parse(result[j]));
}
else if (fieldtypes[j] == "System.DateTime")
{
myCommand11.Parameters.AddWithValue(fields[j], DateTime.Now);
}
}
Console.WriteLine(sql11);
myCommand11.ExecuteNonQuery();
}
}
}
这也不起作用。我认为 ? 没有被正确替换。
无论如何,请帮我修复它,以便我可以正确更新。