473,695 Members | 2,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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

dsLocalDataSet. user_postRow newRow =
dsLocalDataSet1 .user_post.Newu ser_postRow();
newRow.post_tex t = this.lblHiddenM essageStorage.T ext;
newRow.post_dat etime = System.DateTime .Now;
dsLocalDataSet1 .user_post.Addu ser_postRow(new Row);
this.oleDbUserP ostAdapter.Upda te(dsLocalDataS et1.user_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 5084
be*****@peacefi re.org (Bennett Haselton) wrote in message news:<e6******* *************** ****@posting.go ogle.com>...
Suppose I add a new row to a table in a dataset, and then I use an
OleDbDataAdapte r to add that new row to a SQL Server database using
OleDbDataAdapte r.Update(), as in the following code:

dsLocalDataSet. user_postRow newRow =
dsLocalDataSet1 .user_post.Newu ser_postRow();
newRow.post_tex t = this.lblHiddenM essageStorage.T ext;
newRow.post_dat etime = System.DateTime .Now;
dsLocalDataSet1 .user_post.Addu ser_postRow(new Row);
this.oleDbUserP ostAdapter.Upda te(dsLocalDataS et1.user_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 (OleDbConnectio n 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.
*/
OleDbDataAdapte r objAdapter = new OleDbDataAdapte r(
"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("GetL astInsertID called but @@IDENTITY returned
nothing");
}
int nID = System.Int32.Pa rse(strID);
return nID;
}

and the code that calls the function:
dsLocalDataSet. wbuserRow newRow =
this.dsLocalDat aSet1.wbuser.Ne wwbuserRow();
newRow.username = "abc";
newRow.password _hash = "def";
newRow.email_ad dress = "ghi";
this.dsLocalDat aSet1.wbuser.Ad dwbuserRow(newR ow);

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

this.oleDbWbuse rAdapter.Update (dsLocalDataSet 1.wbuser);
Response.Write( "last insert: " +
DatabaseUtils.G etLastInsertID( this.oleDbLocal Connection).ToS tring() +
"<br>\n");
this.oleDbLocal Connection.Clos e();

Nov 18 '05 #2

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

Similar topics

0
1141
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 file), but for some reson the text file is not written to durring the update. Please help. .. ..
1
4471
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 help in advance.
2
3814
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? public void CopyDataSet(int start, int end) { OleDbDataAdapter sourceAdapter = new OleDbDataAdapter("SELECT * FROM " + "WHERE ID > " + (start - 1).ToString() + " AND .id < " + (end + 1).ToString(), connectionString
9
5270
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 INTO Table ( ID, Cod, CodArt, Q1, DataUscita ) VALUES (pID, pCod, pCod, pQ1, pDataUscita);
5
1931
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" Fields: fNumber Numeric fString VarChar(50)
4
1634
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 reasons and can't be changed by me. What I was wondering is what is the bet way to populate the MS-Access DB. The DB will only contain 6 tables which will have a very small amount of data in them. I have tried to use ADO.Net to read the data
2
2329
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 data.(2 tables) Do someone has a good sample code to help me? Many thanks in advance, Marc.
2
2928
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 draging Table1 to Form2. The select command works fine, but when I change the data and call update command I get a syntax error: System.Data.OleDb.OleDbException was unhandled ErrorCode=-2147217900 Message="Syntax error in UPDATE statement."...
7
2139
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 CType(Me.FindControl("admin" & CStr(section("buttontext")).Replace(" ", "")), adminsection2).RefreshSection() Next End Sub
0
8619
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9112
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8975
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8826
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8818
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7652
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
2996
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2261
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1971
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.