473,414 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

how do I get the ID of a row I just added using OleDbDataAdapter.Update() ?

Suppose I add a new row to a table in a dataset, and then I use an
OleDbDataAdapter to add that new row to a SQL Server database using
OleDbDataAdapter.Update(), as in the following code:

dsLocalDataSet.user_postRow newRow =
dsLocalDataSet1.user_post.Newuser_postRow();
newRow.post_text = this.lblHiddenMessageStorage.Text;
newRow.post_datetime = System.DateTime.Now;
dsLocalDataSet1.user_post.Adduser_postRow(newRow);
this.oleDbUserPostAdapter.Update(dsLocalDataSet1.u ser_post);

How do I get the ID in the underlying database, of the new row that I
just added?

It might not be the same as the ID of the row that was just added to
the DataSet table. Even if new IDs are generated sequentially in both
the underlying database table and in the DataSet table, and say the
records already in the table had IDs 1, 2, 3, 4, and 5, when I add the
new row to the DataSet table it will get ID 6. However, in the
meantime, some other process might have added a new row to the table
in the underlying database, so that when the row actually gets added
through adapter's Update() method, in the database it will get ID 7.
So I can't just look at the ID of the row in the DataSet.

In MySQL you can do SELECT LAST_INSERT_ID() to get the last
automatically generated value that was inserted into an AUTO_INCREMENT
column by your current connection. Is there an equivalent for SQL
Server? (Or even better, a way to get the value using the built-in
functions of the typed DataSet, so you don't have to get it
inelegantly passing a raw command to SQL Server, which is error-prone
in case you ever want to switch to a different data source type, etc.)

-Bennett
Nov 18 '05 #1
1 5039
be*****@peacefire.org (Bennett Haselton) wrote in message news:<e6**************************@posting.google. com>...
Suppose I add a new row to a table in a dataset, and then I use an
OleDbDataAdapter to add that new row to a SQL Server database using
OleDbDataAdapter.Update(), as in the following code:

dsLocalDataSet.user_postRow newRow =
dsLocalDataSet1.user_post.Newuser_postRow();
newRow.post_text = this.lblHiddenMessageStorage.Text;
newRow.post_datetime = System.DateTime.Now;
dsLocalDataSet1.user_post.Adduser_postRow(newRow);
this.oleDbUserPostAdapter.Update(dsLocalDataSet1.u ser_post);

How do I get the ID in the underlying database, of the new row that I
just added?

It might not be the same as the ID of the row that was just added to
the DataSet table. Even if new IDs are generated sequentially in both
the underlying database table and in the DataSet table, and say the
records already in the table had IDs 1, 2, 3, 4, and 5, when I add the
new row to the DataSet table it will get ID 6. However, in the
meantime, some other process might have added a new row to the table
in the underlying database, so that when the row actually gets added
through adapter's Update() method, in the database it will get ID 7.
So I can't just look at the ID of the row in the DataSet.

In MySQL you can do SELECT LAST_INSERT_ID() to get the last
automatically generated value that was inserted into an AUTO_INCREMENT
column by your current connection. Is there an equivalent for SQL
Server? (Or even better, a way to get the value using the built-in
functions of the typed DataSet, so you don't have to get it
inelegantly passing a raw command to SQL Server, which is error-prone
in case you ever want to switch to a different data source type, etc.)

-Bennett


Well I found how to do this -- in SQL Server, you call SELECT
@@IDENTITY to get the last automatically inserted ID, however it's
only valid if the connection has not been closed since the update
occurred for which you're trying to get the last inserted ID. So if
you just call a data adapter's Update() method, and the connection was
in the closed state before you called it, the connection will be
closed again when Update returns, and you'll lose the information
about the last inserted ID. So you have to put the adapter's
connection object in the Open state first, then call Update() and then
do a SELECT @@IDENTITY query.

Here's a utility function that does it:

public static int GetLastInsertID(OleDbConnection conn)
{
/*
* The connection object must be open at the time this method
* is called, and the connection cannot have been closed since
* the insertion occurred for which you are trying to get the
* last inserted ID. Otherwise, an exception will be thrown.
*/
OleDbDataAdapter objAdapter = new OleDbDataAdapter(
"SELECT @@IDENTITY AS 'Identity';", conn
);
DataSet ds = new DataSet();
objAdapter.Fill(ds, "tablename");
string strID = ds.Tables["tablename"].Rows[0]["Identity"].ToString();
if (strID == "")
{
throw new Exception("GetLastInsertID called but @@IDENTITY returned
nothing");
}
int nID = System.Int32.Parse(strID);
return nID;
}

and the code that calls the function:
dsLocalDataSet.wbuserRow newRow =
this.dsLocalDataSet1.wbuser.NewwbuserRow();
newRow.username = "abc";
newRow.password_hash = "def";
newRow.email_address = "ghi";
this.dsLocalDataSet1.wbuser.AddwbuserRow(newRow);

// must open connection first or GetLastInsertID won't work
this.oleDbLocalConnection.Open();

this.oleDbWbuserAdapter.Update(dsLocalDataSet1.wbu ser);
Response.Write("last insert: " +
DatabaseUtils.GetLastInsertID(this.oleDbLocalConne ction).ToString() +
"<br>\n");
this.oleDbLocalConnection.Close();

Nov 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: foobar | last post by:
I'm exporting data from sqlserver into a text file. I don't want to use a linked server or DTS. I have no problem getting the data into the correct dataset (the dataset linked to the text...
1
by: JH | last post by:
I have a comma delimited file and I want to export it to an MS access table already designed with appropriate field names. How do I do this programmatically using VB.NET or C#? Thanks for any...
2
by: Son Ha | last post by:
I want to copy some record from a Access database to another Access DB. My code as follow but not working. The destAdapter.Update() return 0 record affected. Tell me what's wrong in my code? ...
9
by: joun | last post by:
Hi all, i'm using this code to insert records into an Access table from asp.net, using a stored procedure, called qry_InsertData: PARAMETERS Long, Long, Text(20), Long, DateTime; INSERT...
5
by: joun | last post by:
As suggested by Cor Ligthert, i've created a simpler sample, with the same problem; this is the full source code, so everyone can try itself: Access database "dati.mdb": Tables: "myTable"...
4
by: JPO | last post by:
Hi there, I'm trying to use MSAccess as a "container" to move data around from one MS-SQL server DB to another. This is basically already a design decision that has been made for a lot of...
2
by: Scotty | last post by:
I get stuck to write an update, insert and delete command, i am looking for some help to start Whats the best way to update 2 tables toe the database (Access) below my code used to load my...
2
by: explode | last post by:
I made nova oledbdataadapter select update insert and delete command and connection veza. dataset is Studenti1data, I made it by the new data source wizard,and made datagridview and bindingsource...
7
by: Nathan Sokalski | last post by:
I have a page which I dynamically add several usercontrols (*.ascx files) to using the following code: Public Sub Refresh() For Each section As DataRow In Me.GetSections().Rows...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.