Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot perform INSERT INTO using DateTime to save timestamp in MS Access

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.");
  }
}
like image 698
Programming Newbie Avatar asked Mar 26 '26 07:03

Programming Newbie


2 Answers

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 });
like image 56
LarsTech Avatar answered Mar 27 '26 20:03

LarsTech


Try setting the command text before setting the parameters... This may be nothing, but I've never seen it done in that order...

like image 40
therealmitchconnors Avatar answered Mar 27 '26 21:03

therealmitchconnors



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!