At first I tried this:
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();
Now this WORKED when I omitted the string and datetime conditions so that it only updated the int and boolean. So it has something to do with a syntax error when I try to update a field where the type is a string.
Then I heard that you have to use parameters when writing to an .mdb file, so I tried this:
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();
}
}
}
Which did not work either. I don't think the ?'s are being replaced properly.
Anyway, please help me fix it so that I can update properly.
Instead of having to mess around with the UPDATE query string for Access, which is easily prone to syntax errors, I just created a DataTable object and SELECTed the row I wanted to UPDATE. I then updated the table via an array of the elements that I wanted to change, then updated the table back to the server using an adapter. This worked out well without me worrying about the syntax! :)
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.