database says that it is inserting, but there are no records
I'm sending a command to the database and it is returning that 1 rows are affected, but when i look inside the database, there are no records. I am receiving no errors. I checked to make sure the string was building correctly and it is. Any ideas? I'm not using parameterized queries here, I know. I will later. Here is the code from the database layer:
public int InsertStartTime(certificate cert, DateTime startTime, string lineNumber)
{
string sql = "INSERT INTO checkLog(userID,lineNumber,startTime) VALUES(" +
cert.userID + ", '" + lineNumber + "', '" + startTime + "');";
int result = 0;
try
{
conn.Open();
comm.CommandText = sql;
result = comm.ExecuteNonQuery();
}
catch (Excepti开发者_C百科on ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
MessageBox.Show(result.ToString() + " rows affected");
return result;
}
Using an access 2000 db file:
string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\assets\users.mdb;Persist Security Info=True";
Right click your database file in VS and look at the properties. Is it set to "Copy Always"? By default, visual studio will make a copy of your database for debugging and any changes will be made only to this copy and will not be reflected in the original. You can set it to copy "Never" if you want to work on the "real" database file even in debug mode.
Depending on the database / data provider you are using, your SQL command may not be executing in auto-commit mode.
Try committing your transaction explicitly. Something like this:
conn.Open();
using (var tran = conn.BeginTransaction()) {
comm.Transaction = tran; // Possibly redundant, depending on database.
comm.CommandText = sql;
result = comm.ExecuteNonQuery();
tran.Commit();
}
Nobody else pointed this out so I will. PLEASE DO NOT USE SQL this way. Use parameters. You leave yourself wide open to sql attacks otherwise.
string sql = "INSERT INTO checkLog(userID,lineNumber,startTime) VALUES(@ID, @line, @starttime);
try
{
conn.Open();
comm.CommandText = sql;
comm.Parameters.Add("ID").Value = cert.userID;
comm.Parameters.Add("line").Value = lineNumber ;
comm.Parameters.Add("starttime").Value = startTime ;
result = comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
精彩评论