我试图通过我的C#Web应用程序更新Access数据库,但我目前在WHERE语句中遇到问题,没有更新记录而没有返回任何错误。
我尝试更新文本字段,WHERE语句中的条件是整数。
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = @Title WHERE ID = @ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@Title", TextBox1.Text);
cmd.Parameters.AddWithValue("@ID", param2);
我甚至尝试过这样做
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("?", TextBox1.Text);
cmd.Parameters.AddWithValue("?", param2);
但它还没有更新!
我发现试图修复它的是当我用单引号之间的字符串替换第一个参数时(见下文),它实际上更新了表。
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = 'test' WHERE ID = @ID");
你们有没有人知道为什么会这样?
编辑:这是完整的代码
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = @Title WHERE ID = @ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@Title", TextBox1.Text);
cmd.Parameters.AddWithValue("@ID", param2);
conn.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
编辑2:
在尝试设置数据类型后,这是我的代码,它仍然无法正常工作
为了澄清,我的Access数据库ID是" AutoNumber"标题是"长文"
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("Title", TextBox1.Text).OleDbType = OleDbType.VarChar;
cmd.Parameters.AddWithValue("ID", param2).OleDbType = OleDbType.Integer;
conn.Open();
try
{
var recordsUpdated = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
当我检查recordsUpdated的值时,它返回" 1"但数据库没有更新。
答案 0 :(得分:1)
您需要调用执行该语句的ExecuteNonquery。
// your OleDbConnection should also be wrapped in a using statement to ensure it is closed
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open(); // open the connection
using(OleDbCommand cmd = new OleDbCommand("UPDATE Data SET Title = ? WHERE ID = ?")) // wrap in using block because OleDbCommand implements IDisposable
{
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("Title", TextBox1.Text).OleDbType = OleDbType.VarChar; // Title, also set the parameter type
cmd.Parameters.AddWithValue("ID", param2).OleDbType = OleDbType.Integer; // ID, I am guessing its an integer but you should replace it with the correct OleDbType
var recordsUpdated = cmd.ExecuteNonQuery(); // execute the query
// recordsUpdated contains the number of records that were affected
}
}
当我检查recordsUpdated的值时,它返回" 1"但数据库没有更新。
如果返回1,则更新1条记录。这里有2个故障排除提示。
param2
的值并在Access中的select语句中手动使用它,以查看该记录的标题列SELECT Title FROM Data WHERE ID = [id here]
。在调试中也获取TextBox1.Text
的值,并根据手动执行的select
查询返回的值检查此值。