Get Auto id when inserting record into ms Access

J

James Alba

Hey all,

I am accessing an ms access database using .NET and C#. Like so,

/* Create the database connection. */
connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=" + Name);
connection.Open();

And all is good.

My "ticket" table has the setup: auto number (PK), name and event_id.

I am successfully inserting records into the "ticket" table, BUT HOW can I
get the auto number of my PK that MS Access assigns???

I really need this PK!!!

for (int i = 0; i < j; ++i)
{
OleDbCommand c = new OleDbCommand("insert into ticket (name, event)
values('" + Customer + "', '" + ID + "')", connection);
c.ExecuteNonQuery();
}

Thankyou all!
 
D

dd

First thing crosses my mind is max(ID).
The last record inserted should get the max number in the auto number field.

-Duy
 
S

Steve

I just did this morning. I was't terribly concerned with elegance because I
know once proof of concept gets signed off, we will move it to SqlServer
where stored procedures make this easy.

Anyway, what I do is use Access Queries(Access' version of Sql sprocs)
I have one for the insert that take the parameters of the insert, say
_userName and _email
then another to fetch the ID where UserName = _username and Email = _email.

Since I have already set up the command object with the parameters, it's a
matter of calling ExecuteNonQuery for the update, then ExecuteReader for the
ID changing the Command object's CommandText to reflect the correct query.

It works. Not the prettiest thing, but works.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top