Question

im performing an insert sql command in c# program using oledb methods as the code down will show.

the action is performed and it even shows me a message I've put there to indicate if it worked or not but when i open the database manually the data i inserted using the code don't appear

im using c# and Acess as database

the tables in the database of type

time = time/date

header = text

importance = int

body = text

as for the variables in the code all string but im using a datetimepicker to allow the user to choose the date by picking instead of typing it

OleDbConnection conn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Database.accdb");
conn1.Open();
string sql = "INSERT INTO notes ([time], [Header], [importance], [body])" + "VALUES ('" + dateTimePicker1.Value + "', '" + textBox1.Text + "','" + int.Parse(comboBox1.Text) + "','" + textBox2.Text + "');";
OleDbCommand cmd2 = new OleDbCommand(sql, conn1);
try
{
    OleDbDataReader rd2 = cmd2.ExecuteReader();
    conn1.Close();
    MessageBox.Show("Added");
}
catch(Exception ex)
{
    MessageBox.Show(ex.ToString());
}
this.Close();
Was it helpful?

Solution

Problem1 : You are calling ExecuteReader() method while Inserting Data into Database.

Solution1 : You need to use ExecuteNonQuery() method to execute INSERT,UPDATE or DELETE commands.

Replace This :

OleDbDataReader rd2 = cmd2.ExecuteReader();

With This:

cmd2.ExecuteNonQuery();

Problem 2: you are assigning the DateTime value into time column as string. if the string format is not supported by time column then INSERT operation will not be successfull.

Solution 2: so i would suggest you to use Parameterised queries for following two reasons:

  1. mainly parameterised queries prevent SQL Injection Attacks to happen.
  2. parameterised queries will send the parameters with proper datatypes.

Suggestion : while checking for the command execution status you need to read the return value of the ExecuteNonQuery() method.because it returns the total number of rows inserted into table after command execution. so you can read it and display success message only when the count returned is greater than zero.

Complete Code:

    int status=0;
    OleDbConnection conn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Database.accdb");
    conn1.Open();
    string sql = "INSERT INTO notes ([time], [Header], [importance], [body]) " + "VALUES (?,?,?,?);";
    OleDbCommand cmd2 = new OleDbCommand(sql, conn1);
    cmd2.Parameters.AddWithValue("@time",dateTimePicker1.Value);
    cmd2.Parameters.AddWithValue("@Header",textBox1.Text);
    cmd2.Parameters.AddWithValue("@importance",int.Parse(comboBox1.Text) );
    cmd2.Parameters.AddWithValue("@body",textBox2.Text);
    try
    {
       status=cmd2.ExecuteNonQuery();
       conn1.Close();
       if(status>0)
       MessageBox.Show("INSERT Command Executed Successfully!");
       else
       MessageBox.Show("INSERT Command Failed!");
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    this.Close();

OTHER TIPS

am not really a c-sharp programmer but you actually shouldn't assign cmd.executeReader() to a variable I think you should just write the command on that line so it executes

You need to use the ExecuteNonQuery to execute the insert query on the database.

cmd2.ExecuteNonQuery();

ExecuteReader used when you want to retrieve the data from database like in SELECT query.

Also please use parameterized query to avoid Sql Injection

string sql = "INSERT INTO notes ([time], [Header], [importance], [body]) VALUES (@time, @header, @importance, @body);";

cmd2.Parameters.AddWithValue("@time", Convert.ToDateTime(dateTimePicker1.Value));
cmd2.Parameters.AddWithValue("@header", textBox1.Text);
cmd2.Parameters.AddWithValue("@importance", Convert.ToInt32(comboBox1.Text));
cmd2.Parameters.AddWithValue("@body", textBox2.Text);

cmd2.ExecuteNonQuery();

try something like this hope it helps

OleDbConnection conn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Database.accdb");
        conn1.Open();
        string sql = "INSERT INTO notes ([time], [Header], [importance], [body]) " + "VALUES (?,?,?,?);";
        OleDbCommand cmd2 = new OleDbCommand(sql, conn1);
        cmd2.CommandType = CommandType.Text;
        cmd2.Parameters.Add("@time", OleDbType.Date).Value = DateTime.Parse(dateTimePicker1.Value);
        cmd2.Parameters.Add("@Header", OleDbType.VarChar).Value = textBox1.Text;
        cmd2.Parameters.Add("@importance", OleDbType.Integer).Value = int.Parse(comboBox1.Text);
        cmd2.Parameters.Add("@body", OleDbType.VarChar).Value = textBox2.Text;
        try
        {
            status = cmd2.ExecuteNonQuery();
            conn1.Close();
            if (status > 0)
                MessageBox.Show("INSERT Command Executed Successfully!");
            else
                MessageBox.Show("INSERT Command Failed!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        this.Close();

you can't use cmd2.ExecuteReader to insert the record into database you have to use cmd2.ExcuteNonQuery(); to perform operation such as INSERT UPDATE OR DELETE.

OleDbConnection conn1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = Database.accdb");
      conn1.Open();
    string sql = "INSERT INTO notes ([time], [Header], [importance], [body]) VALUES ('" + dateTimePicker1.Value + "', '" + textBox1.Text + "','" + int.Parse(comboBox1.Text) + "','" + textBox2.Text + "');";
    OleDbCommand cmd2 = new OleDbCommand(sql, conn1);
    try
    {
       cmd2.ExecuteNonQuery();
        
        MessageBox.Show("Added");
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
    conn1.Close();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top