Search code examples
c#winformsms-accessoledb

How to insert a record with a primary key in ms access database c#


I am using the following command for inserting a record in an MS Access database:

OleDbCommand cmd = new OleDbCommand("insert into Table1 values('" + Name + "','" +
Symbol + "','" + D + "','" + Red + "','" + RedBuy + "','" + RedSell + "','" + 
SBIntraBuy + "','" + SBTR1Buy + "','" + SBTR2Buy + "','" + SBTR3Buy + "','" + 
SBIntraSell + "','" + SBTR1Sell + "','" + SBTR2Sell + "','" + SBTR3Sell + "','" + RSTL
+ "','" + Green + "');", con);

I want to add a column before Name called CustomerId with a Primary key. I don't know how to insert it with primary key. What i should add in my command for primary key?

There would be a great appreciation if someone could help me.

Thanks In Advance.

Check this link for screen shot of the table layout.


Solution

  • If your key is auto increment, then you don't need to. The database will do it for you. If your key is not auto increment, consider changing it. It's really neat!

    Also, please consider using binding instead of building a full insert query.

    Suppose the following table:

    Table1
    PK (auto_increment)
    Name
    Symbol
    

    What you will want to do is:

    OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (?,?)");
    cmd.Parameters.Add(new OleDbParameter("@Name",Name));
    cmd.Parameters.Add(new OleDbParameter("@Symbol",Symbol));
    

    or (safer):

    OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (@Name,@Symbol)");
    cmd.Parameters.Add(new OleDbParameter("@Name",Name));
    cmd.Parameters.Add(new OleDbParameter("@Symbol",Symbol));
    

    And finally:

    cmd.ExecuteNonQuery();