您好我为我的网站制作更新按钮时遇到了麻烦我尝试了很多方法,但似乎无法弄明白。我希望用户输入他们想要更新的客户的ID号,然后根据他们想要更改的列填写文本框。
这是我的代码:
private static OleDbConnection GetConnection()
{
String connString;
connString = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\registration-Db.mdb";
return new OleDbConnection(connString);
}
protected void clientUpdate_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:/Users/Wisal/Documents/Visual Studio 2012/WebSites/WebSite3\registration-Db.mdb");
cn.Open();
OleDbCommand cmd = new OleDbCommand("(Update client set id = " + txt_id.Text + " ,[name] ='" + txt_name.Text + " ,[password] ='" + txt_password.Text +" where id= '" + txt_id.Text + "",cn);
cmd.ExecuteNonQuery();
cn.Close();
}
}
我也试过这个:
private static OleDbConnection GetConnection()
{
String connString;
connString = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\registration-Db.mdb";
return new OleDbConnection(connString);
}
protected void clientUpdate_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = GetConnection();
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("(Update client set id = " + txt_id.Text + " ,[name] ='" + txt_name.Text + " ,[password] ='" + txt_password.Text +" where id= '" + txt_id.Text + "",myConnection);
cmd.ExecuteNonQuery();
myConnection.Close();
}
}
通过这个,我得到了"联合查询中的语法错误。"
我也试过这个:
protected void clientUpdate_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = GetConnection();
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("Update client set [name] = ? [password] = ? where id= ?", myConnection);
cmd.Parameters.AddWithValue("", txt_id.Text);
cmd.Parameters.AddWithValue("", txt_name.Text);
cmd.Parameters.AddWithValue("", txt_password.Text);
cmd.ExecuteNonQuery();
myConnection.Close();
}
}
答案 0 :(得分:2)
我稍微更新了您的代码:
private static OleDbConnection GetConnection()
{
var connString = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\Wisal\Documents\Visual Studio 2012\WebSites\WebSite3\registration-Db.mdb";
return new OleDbConnection(connString);
}
protected void clientUpdate_Click(object sender, EventArgs e)
{
using(var myConnection = GetConnection())
{
myConnection.Open();
// You should be using a parameterized query here
using (var cmd = new OleDbCommand("Update client set [name] = ?, [password] = ? where id = ?", myConnection))
{
cmd.Parameters.AddWithValue("name", txt_name.Text);
cmd.Parameters.AddWithValue("password", txt_password.Text);
cmd.Parameters.AddWithValue("id", txt_id.Text);
cmd.ExecuteNonQuery();
}
}
}
答案 1 :(得分:0)
您的单引号不匹配?
您的id
字段是int还是string?我假设它是int类型。而且您不需要更新id
字段,因为它与where子句中的值相同。
试试这个:
OleDbCommand cmd = new OleDbCommand("Update client set [name] ='" + txt_name.Text + "' ,[password] ='" + txt_password.Text +"' where id= " + txt_id.Text,myConnection);