locked
How do you insert into an Access database? RRS feed

  • Question

  • User1940910349 posted

    I have a table that is using an AutoNumber as its primary key. It won't let me exclude the ID though when I insert a row so I have been running the MAX function on the ID's and then just adding one to it. But I dont think I'm doing it right because if I am reading this right then ExecuteScalar (or ExecuteNonQuery) returns the number of rows affected by the SQL statement, it doesn't return the actual MAX value. Which, you know, it does work like that but it just doesn't seem like the right way to do it. Below is the code that I am using, but would like to improve.

     

    OleDbCommand command = new OleDbCommand();

    command = conn.CreateCommand();

    string strSQL;

    strSQL = "SELECT Max(ID) FROM Cars";

    command.CommandType = CommandType.Text;

    command.CommandText = strSQL;

    int count = Convert.ToInt32(command.ExecuteScalar());
    Wednesday, February 25, 2009 9:11 PM

Answers

  • User-1199946673 posted

    I'm not quit sure what you're trying to achieve? An autonumber field is automaticaly included while inserting a record, so you don't need to include that field and its valus in the insert statement. If you want to retriev the identity of the most recently added record, read this

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 26, 2009 2:22 AM

All replies

  • User1650982503 posted

     you can use a sql datareader

     

    rdr As SqlDataReader = command.ExecuteReader 

     

     

    Wednesday, February 25, 2009 10:05 PM
  • User-1199946673 posted

    I'm not quit sure what you're trying to achieve? An autonumber field is automaticaly included while inserting a record, so you don't need to include that field and its valus in the insert statement. If you want to retriev the identity of the most recently added record, read this

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 26, 2009 2:22 AM