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();
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:
parameterised queries
prevent SQL Injection Attacks
to happen.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();