我有一个数据库(我使用MS ACCESS)我有这个插入代码,我可以读取数据但写入时出错,我按照说明但它没有工作 这是我的代码
OleDbConnection con = new OleDbConnection(@" provider=Microsoft.ace.Oledb.12.0; data source=\\sisc-erelim\4_Printing\VTDB\DB\VirginiTEADB2.accdb; Persist Security Info=False");
private void button1_Click(object sender, EventArgs e)
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Accountstbl (Username, Password)" + "VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Parameters.AddWithValue("@Username", textBox1.Text);
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.ToString();
}
我总是遇到这个错误,
System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at VirginiTEAcorp.Form3.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\12-014s\My Documents\applications\Database\WindowsFormsApplication1\Form3.cs:line 34
答案 0 :(得分:9)
您定义了@Username
和@Password
参数,但您从未在sql命令中使用过。
怎么样?
cmd.CommandText = "INSERT INTO Accountstbl (Username, [Password]) VALUES (@Username, @Password)";
cmd.Parameters.AddWithValue("@Username", textBox1.Text);
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
另外,您应该在sql命令的方括号中使用Password
,例如[Password]
,因为它在MS Access中是reserved keyword
。
如果不这样做会导致错误,如;
关键字“密码”
附近的语法不正确
答案 1 :(得分:1)
尝试改变这种方式
cmd.CommandText = "INSERT INTO Accountstbl (Username, Password) VALUES (@Username,@Password)";
答案 2 :(得分:0)
插入语句中需要一个空格:
ssword)" + "VALUES ('"
例如,在你的陈述中,你已连接而没有允许空格。
应该是:
ssword)" + " VALUES ('"
例如。
答案 3 :(得分:0)
你可以拥有:
cmd.CommandText = "INSERT INTO Accountstbl (Username, [Password]) VALUES (@Username,@Password)";
cmd.Parameters.AddWithValue("@Username", textBox1.Text);
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
我希望这会奏效。
欢呼行动。