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:
- mainly
parameterised queries
preventSQL Injection Attacks
to happen. parameterised queries
will send theparameters
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();