Solved

c# msaccess return newly inserted rows id

Posted on 2014-03-14
4
245 Views
Last Modified: 2014-03-25
Hi

I have a networked database, with a number of users


I have a situation where I need to insert a record into a table, and return the autonumber ID generated by access, so that the user can add records to another table using the id from the first table as the foreign key.

I have used the following sql statement

"Select @@Identity from " + table;

which works most times, however on the odd occasion it appears to be returning either nothing or the id from the previous record.

Is there any way to ensure that the query returns the correct value each time?

here is my code to insert data

  public int InsertData(string table, string[] fields, string[] values)
        {
            int id = 0;
            OleDbConnection con = new OleDbConnection(connectionstring);
            string query2 = "Select @@Identity from " + table;
            con.Open();
            string myFields = "";
            string myValues = "";

            foreach (string f in fields)
            {
                myFields += f + ", ";
                myValues += "?,";

            }

            if (myFields.Length > 0)
            {
                myFields = myFields.Substring(0, myFields.Length - 2);
                myValues = myValues.Substring(0, myValues.Length - 1);
            }

            OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("INSERT INTO " + table + " (" + myFields + ") Values (" + myValues + ") ", con);

            foreach (string v in values)
            {
                cmd.Parameters.AddWithValue("?",v);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            cmd.CommandText = query2;
            id = Convert.ToInt32(cmd.ExecuteScalar());
            
            con.Close();


            return id; 
        }

Open in new window

0
Comment
Question by:cycledude
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 63

Assisted Solution

by:Fernando Soto
Fernando Soto earned 500 total points
ID: 39930296
Hi cycledude;

According to this Microsoft article you will need two OleDbCommand connections. The article shows how to do this.

HOW TO: Retrieve the Identity Value While Inserting Records into Access Database By Using Visual C# .NET
0
 

Author Comment

by:cycledude
ID: 39930406
thanks Fernando

Any ideas how I can get that to work with my code?
0
 

Accepted Solution

by:
cycledude earned 0 total points
ID: 39941813
in the end I had to use a timestamp when entering the row, then use a while loop to repeat the process of acquiring the id every 1 second until the correct id was found.
0
 

Author Closing Comment

by:cycledude
ID: 39952707
thanks for the assist
0

Featured Post

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes two methods for creating a combo box that can be used to add new items to the row source -- one for simple lookup tables, and one for a more complex row source where the new item needs data for several fields.
You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
Familiarize people with the process of utilizing SQL Server views from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Access…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question