I wrote a form based program in C# that uses MS access database to store its data.
In the MDB file I have a single table named __item__
in the table there are 7 fields of which the first one is called __item_id__ and it is the auto indexer of the table, so when I add new entry it should auto increase each time, so I won’t have 2 entry’s with the same id.
In the program I use the following code (this isn’t the full code, just the relevant one):
using System.Data.OleDb;
private OleDbConnection con; // create connection
private OleDbCommand cmd; // create command
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = d:\\library0.1\\DB.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Item VALUES (@item_name, @creator_name,@publishing_name,@item_type,@genre,@year_publication);";
con.Open(); // open the connection
cmd.ExecuteNonQuery();
con.Close();
this code will give me an error __ExecuteNonQuery__ claiming I have too few fields.
It wants me to enter the __item_id__ manually, like this:
cmd.CommandText = "INSERT INTO Item VALUES (@item_id, @item_name, @creator_name,@publishing_name,@item_type,@genre,@year_publication);";
How can I avoid manual input and have the program auto index the item_id for each new entry?
If you use INSERT INTO without specifying the column list you should provide parameter for all columns.
To avoid the error change your commandtext to: