简体   繁体   English

在MS Access c#中更新多行

[英]Updating Multiple rows in MS Access c#

I am Trying to Update multiple rows in a MS Access DB But every time it gives ERROR IN UPDATE SYNTAX here's my code 我正在尝试更新MS Access数据库中的多行,但是每次它给出更新语法错误时,这是​​我的代码

cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\\Users\\Kalpesh\\Desktop\\Entry.accdb");
sqlstr = "Update Members SET Name=@Name, MobileNo=@MobileNo, Password=@Password, IDType=@IDType, IDNo=@IDNo, AmountPaid=@AmountPaid, Address=@Address, Reg Date = "+DateTime.Now.ToShortDateString()+" WHERE UserName = '" + comboBox4.SelectedItem.ToString() + "'",cn);
cmd = new OleDbCommand(sqlstr, cn);
cmd.Parameters.AddWithValue("@Name", textBox19.Text.ToString());
cmd.Parameters.AddWithValue("@MobileNo", textBox14.Text.ToString());
cmd.Parameters.AddWithValue("@Password", textBox17.Text.ToString());
cmd.Parameters.AddWithValue("@IDType", comboBox5.SelectedItem.ToString());
cmd.Parameters.AddWithValue("@IDNo", textBox11.Text.ToString());
cmd.Parameters.AddWithValue("@AmountPaid", textBox16.Text.ToString());
cmd.Parameters.AddWithValue("@Address", richTextBox3.Text.ToString());

cn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
cn.Close();

Name and Password are reserved keywords in MS Access. NamePassword是MS Access中的保留关键字

If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets ( [ ] ). 如果已经使用了保留字,则可以在每次出现该字时用方括号( [ ] )来避免出现错误消息。 However, the best solution is to change the name to a nonreserved word . 但是,最好的解决方案是将名称更改为非保留字

You need to use Reg Date with square brackets like [Reg Date] also since it has space. 您还需要将Reg Date与方括号一起使用,例如[Reg Date]因为它有空格。 Parameterized your Reg Date and UserName column values as you did for other columns. 就像其他列一样,对“ Reg Date和“ UserName列值进行参数化。 Like; 喜欢;

... [Reg Date] = @reg WHERE UserName = @user ...
cmd.Parameters.AddWithValue("@reg", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("@user", comboBox4.SelectedItem.ToString());

Also use using statement to dispose your OleDbConnection and OleDbCommand . 也可以使用using语句来处理OleDbConnectionOleDbCommand

string conString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\\Users\\Kalpesh\\Desktop\\Entry.accdb";
using(OleDbConnection cn = new OleDbConnection(conString))
using(OleDbCommand cmd = cn.CreateCommand())
{
  // Do your work..
}

由于没有关于语法问题的明确错误消息,我猜想它在日期前后缺少单引号,请尝试以下操作:

RegDate = '"+DateTime.Now.ToShortDateString()+"'

Problem is here 问题在这里

 "Reg Date = "+DateTime.Now.ToShortDateString()+"

Try this 尝试这个

 "[Reg Date] = #" + DateTime.Now.ToShortDateString() + "# "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM