问题
I have a database and i use MS ACCESS 2007. I wanted to insert data into the database through textbox. I have this code below but I got errors.
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb");
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();
}
and here are the errors
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
回答1:
You have declared parameters but not used them,If you are using following statement then there is no need to use parameters
cmd.CommandText = "INSERT INTO Accountstbl (Username, Password)" + "VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')";
But if you want to use parameters then you neeed to change commandtext as follow...
cmd.CommandText = "INSERT INTO Accountstbl (Username, Password) VALUES (@UserName,@Password)";
回答2:
maybe you can try this code
private void button1_Click(object sender, EventArgs e)
{
try
{
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO userinfo (FirstName, LastName, Age, Address, Course)" + "VALUES (@First_Name, @Last_Name, @Age, @Address, @Course)";
cmd.Parameters.AddWithValue("@First_Name", textBox1.Text);
cmd.Parameters.AddWithValue("@Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Age", textBox3.Text);
cmd.Parameters.AddWithValue("@Address", textBox5.Text);
cmd.Parameters.AddWithValue("@Course", textBox5.Text);
cmd.Connection = conn;
conn.Open();
clear();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Data Added!");
conn.Close();
}
dataholder();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
if you'll declare parameters. you may have to used them in a way. Hope it helps :)
来源:https://stackoverflow.com/questions/15105872/i-cant-insert-data-in-ms-access-database-through-textbox