Data is not saved in MS Access database
I have a visual C# project and I'm trying to insert data in a MS Access Database when I press a button. Here is the code:
private void button1_Click(object sender, EventArgs e)
{
try
{
开发者_C百科 OleDbDataAdapter adapter=new OleDbDataAdapter();
adapter.InsertCommand = new OleDbCommand();
adapter.InsertCommand.CommandText =
"insert into Candidati values ('" + maskedTextBox1.Text.Trim() + "','" + textBox1.Text.Trim() + "', '" + textBox2.Text.Trim() + "', '" + textBox3.Text.Trim() + "','" + Convert.ToDouble(maskedTextBox2.Text) + "','" + Convert.ToDouble(maskedTextBox3.Text) + "')";
con.Open();
adapter.InsertCommand.Connection = con;
adapter.InsertCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inregistrare adaugata cu succes!");
maskedTextBox1.Text = null;
maskedTextBox2.Text = null;
maskedTextBox3.Text = null;
textBox1.Text = null;
textBox2.Text = null;
textBox3.Text = null;
maskedTextBox1.Focus();
}
catch (AdmitereException exc)
{
MessageBox.Show("A aparut o exceptie: "+exc.Message, "Eroare!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The connection string is:
private static string connectionString;
OleDbConnection con;
public AddCandidati()
{
connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=Admitere.mdb";
con = new OleDbConnection(connectionString);
InitializeComponent();
}
Where AddCandidati
is the form.
The data is not saved in the database, why? I have the .mdb file in the project folder. What I'm doing wrong? I did not got any exception when I pressed the button.
Your insert command is wrong. You have to specify the names of the columns first, then you give the values for each of those columns.
INSERT INTO tablename (column1, column2, column3) VALUES ('value1', 'value2', 'value3')
精彩评论