Reputation: 145
i'm realising a litel program with windows forms c#, that saves data in ms ACCESS database. i write this code
OleDbConnection connect = new OleDbConnection();
private void button1_Click(object sender, EventArgs e)
{
connect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb";
string fname = textBox1.Text;
string lname = textBox2.Text;
connect.Open();
OleDbCommand cmd = new OleDbCommand(" INSERT INTO user ([nom],[prenom]) VALUES (@fname,@lname)",connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("@fname", fname);
cmd.Parameters.AddWithValue("@lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("erreur" + ex.Source);
connect.Close();
}
}
else
{
MessageBox.Show("probleme connection");
}
}
and i got this error when executing it "error in insert methode" i have not idea the error in insert request. have you an idea
Upvotes: 0
Views: 109
Reputation: 6849
The OLE DB .NET Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.So, Try to use ?
instead of named parameter. for example.
INSERT INTO [user] ([nom],[prenom]) VALUES (?,?)
comand.Parameters.Add("nom", OleDbType.VarChar).Value = fname;
Upvotes: 0
Reputation: 2096
Try this. I added the using
-statements and [
]
-brackets to the query string.
string fname = textBox1.Text;
string lname = textBox2.Text;
using(OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Zied\Documents\Visual Studio 2010\Projects\testerMSAcceess\testerMSAcceess\bin\Debug\zimed.mdb"))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO [user] ([nom],[prenom]) VALUES (@fname,@lname)", conn))
{
try
{
conn.Open();
cmd.Parameters.AddWithValue("@fname", fname);
cmd.Parameters.AddWithValue("@lname", lname);
cmd.ExecuteNonQuery();
MessageBox.Show("ajout ok ");
}
catch (Exception ex) { MessageBox.Show("Erreur" + ex.Source); }
finally { if (conn.State == ConnectionState.Open) { conn.Close(); } }
}
Upvotes: 1