I am trying to save a username and a DateTime object to an MS-Access database but I get a "Syntax error in INSERT INTO statement." When I debug the program I see that the date is being properly passed. Also, I completely removed the DateTime information and used the insert command with just the username and it save correctly, so it has something to do with the DateTime itself but I don't know what. Here is the associated code:
//event handler for Begin Program button
private void btnBeginProgram_Click(object sender, EventArgs e)
{
//assign DateTime object to current computer date/time
busObject.DtDate = DateTime.Now;
//assign input to busObject.UserName property
busObject.UserName = txtEnterName.Text;
//call method to save input data
busObject.SaveData();
this.Close();
}
//properties for variables and objects
public string UserName
{
get { return userName; }
set { userName = value; }
}
public DateTime DtDate
{
get { return dtDate; }
set { dtDate = value; }
}
//method to call SaveData method in ProgramLoginDAL class
public void SaveData()
{
ProgramLoginDAL.SaveData(this);
}
//method to save user input to database
public static void SaveData(ProgramLoginBOL busObject)
{
try
{
OleDbCommand cmd = aConnection.CreateCommand();
String sSQLCommand = "INSERT INTO ProgramLogin (UserName, DateTime) VALUES (?,?)";
cmd.Parameters.AddWithValue("?", busObject.UserName);
cmd.Parameters.AddWithValue("?", busObject.DtDate);
if (aConnection.State == ConnectionState.Closed)
{
aConnection.Open();
}
cmd.CommandText = sSQLCommand;
// Execute the SQL command
cmd.ExecuteNonQuery();
aConnection.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("Error! Data was not saved.");
}
}
Try placing brackets around your field name. It's probably a keyword:
String sSQLCommand = "INSERT INTO ProgramLogin (UserName, [DateTime]) VALUES (?,?)";
For DateTime, you might have to specify the data type:
sSQLCommand .Parameters.Add(
new OleDbParameter("?", OleDbType.Date) { Value = busObject.DtDate });
Try setting the command text before setting the parameters... This may be nothing, but I've never seen it done in that order...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With