我创建了一个代码,用于更新/编辑连接到MS Access的C#程序的计算机/电子产品的详细信息。以下是代码:
OleDbCommand cmd = new OleDbCommand("UPDATE Available SET ProductType = '" + newAvailable.ProductType + "', Brand = '"+ newAvailable.Brand + "', Model = '" + newAvailable.Model + "', SerialNo = '" + newAvailable.SerialNo + "', Remarks = '" + newAvailable.Remarks + "', RAM = '" + newAvailable.RAM + "', HDD = '" + newAvailable.HDD + "', ODD = '" + newAvailable.ODD + "', VideoCard = '" + newAvailable.VideoCard + "', PS = '" + newAvailable.PS + "' WHERE AvailableID = '"+oldAvailable.AvailableID+"'", cnn);
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
AvailableID接受Int32值,其余变量是字符串。该程序是可执行的,但C#检测到错误。
标准表达式中的数据类型不匹配。
我该怎么办?
答案 0 :(得分:10)
我怀疑你没有传递一个正确的参数,可能是AvailableID
,而是尝试以这种方式添加参数:
var cmd = new OleDbCommand
{
Connection = cnn,
CommandType = CommandType.Text,
CommandText = "UPDATE Available SET ProductType = ?, Brand = ?, Model = ?, SerialNo = ?, Remarks = ?, RAM = ?, ODD = ?, VideoCard = ?, PS = ? WHERE AvailableID = ?"
};
cmd.Parameters.Add(new OleDbParameter {Value = newAvailable.ProductType});
cmd.Parameters.Add(new OleDbParameter {Value = newAvailable.Brand});
// add the other parameters ...
作为旁注,通过连接字符串生成查询并不是一个好主意,无论如何应始终使用参数。
答案 1 :(得分:1)
删除(''),因为它们具有整数值
答案 2 :(得分:0)
试试这个
OleDbCommand cmd = new OleDbCommand("UPDATE Available SET ProductType = '" + newAvailable.ProductType + "', Brand = '"+ newAvailable.Brand + "', Model = '" + newAvailable.Model + "', SerialNo = '" + newAvailable.SerialNo + "', Remarks = '" + newAvailable.Remarks + "', RAM = '" + newAvailable.RAM + "', HDD = '" + newAvailable.HDD + "', ODD = '" + newAvailable.ODD + "', VideoCard = '" + newAvailable.VideoCard + "', PS = '" + newAvailable.PS + "' WHERE AvailableID = "+oldAvailable.AvailableID, cnn);
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
答案 3 :(得分:0)
简单的是在此处放置一个调试点并检查查询。复制并直接在访问中运行它并使用数据进行更改。您将找出输入的参数值是错误的。
答案 4 :(得分:0)
我会用这样的东西来实现你想要做的事情。这段代码适用于MS Access 2013
//setting up connection.
OleDbConnection conn = new OledbConnection("connectionstring goes here");
//set the command string query
string cmdStr = "UPDATE Available SET ProductType = ?, Brand = ?, Model = ?, SerialNo = ?, Remarks = ?, RAM = ?, ODD = ?, VideoCard = ?, PS = ? WHERE AvailableID = ?";
//create the command
OleDbCommand cmd = new OleDbCommand(cmdStr,conn);
//add parameters
cmd.Parameters.AddWithValue("@p1",newAvailable.Brand);
cmd.Parameters.AddWithValue("@p2",newAvailable.Brand);
cmd.Parameters.AddWithValue("@p3",newAvailable.SerialNo);
// add all your parameters in the correct order here below .