I have a problem connecting to MS Access DB 2007. Code:
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
try
{
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ Directory.GetCurrentDirectory() +"\\dvd_manager.accdb;Persist Security Info=False;";
Conn.ConnectionString = conn;
Conn.Open();
int i = cbbLocatie.SelectedIndex + 65;
char c = (char)i;
string sql = "INSERT INTO DVD (titel, locatie)VALUES(@titel, @locatie)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param = new OleDbParameter("@titel", txtTitle.Text);
Com.Parameters.Add(Param);
Param = new OleDbParameter("@locatie", c);
Com.Parameters.Add(Param);
Com.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Data is opgeslagen " + sql);
}
catch (Exception ex)
{
MessageBox.Show("Fout opgetreden: " + ex.Message);
}
finally
{
Conn.Close();
}
}
When I run this code, a message appears. This should mean that my data is inserted. But when I open the accdb file, the data is not inserted. What am I doing wrong?
Thnx
Edit: The return value of ExecuteNonQuery () is 1 (I am editing my post because I cannot add comments, when I click add comment, the field is not displayed.)
Edit 2: I created a class with Title and Location properties. Code: private void btnSave_Click (object sender, EventArgs e) {OleDbConnection Conn = new OleDbConnection ();
try
{
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ Directory.GetCurrentDirectory() +"\\dvd_manager.accdb;Persist Security Info=False;";
Conn.ConnectionString = conn;
Medium M = new Medium();
int i = cbbLocatie.SelectedIndex + 65;
char c = (char)i;
M.Location = c;
M.Title = txtTitle.Text;
Conn.Open();
string sql = "INSERT INTO DVD (titel, locatie)VALUES(@titel, @locatie)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param1 = new OleDbParameter("@titel", M.Title);
Com.Parameters.Add(Param1);
OleDbParameter Param2 = new OleDbParameter("@locatie", M.Location);
Com.Parameters.Add(Param2);
int ret = Com.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Data is opgeslagen " + ret);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Fout opgetreden: " + ex.Message);
}
finally
{
Conn.Close();
}
}
Since I still cannot click the add comments button, here is my new code with anonymous sql parameters:
Conn.Open();
string sql = "INSERT INTO DVD (titel, locatie)VALUES(?, ?)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param1 = new OleDbParameter("@p1", OleDbType.VarChar, 1);
Param1.Value = M.Title;
Com.Parameters.Add(Param1);
OleDbParameter Param2 = new OleDbParameter("@p2", OleDbType.VarChar, 255);
Param2.Value = M.Location;
Com.Parameters.Add(Param2);
int ret = Com.ExecuteNonQuery();
Conn.Close();
Martijn