473,609 Members | 2,761 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OleDBDataAdapte r => Insert and Update of data values in a Database

Hi all !
I have a table in my database, which has 3 attributes. IDFailureContro l,
ControlDate and ControlVersion.

In the following function I test, if the date of today allready exists.
Then I would like to write the new ControlDate or Version into the
database. First i update the dataset, then i create a Insertcommand and
call the update-methode. All datas are in the database, but....

1.) If I only use the InsertCommand, without updating the dataset, the
datas would not be inserted to the database....?

2.) At the end I try to get the new created IDFailureContro l
(autoIncrement) , but it does not exist. Why ? how can I get this ID ?
here my code:

public int WriteControlDat e()
{
DateTime currentDate = DateTime.Today;
DataSet currentDateData s = new DataSet();
int iVersion = 0;
int iIndex = 0;

try
{
this.dbConnecti on.Open();

this.dbAdapter. SelectCommand = new OleDbCommand("S ELECT *
FROM FailureControl ORDER BY IDFailureContro l", this.dbConnecti on);
this.dbAdapter. Fill(currentDat eDatas);

if(currentDateD atas.Tables.Cou nt != 0)
{
int iLastRowIndex =
currentDateData s.Tables[0].Rows.Count - 1;
DataRow lastRow =
currentDateData s.Tables[0].Rows[iLastRowIndex];
DateTime lastControlDate = (DateTime)
lastRow["ControlDat e"];

if(lastControlD ate.Equals(curr entDate) == true)
{
iVersion = (int) lastRow["ControlVersion "];
iVersion++;
}
}

DataRow newRow = currentDateData s.Tables[0].NewRow();
newRow["ControlDat e"] = currentDate;
newRow["ControlVersion "] = iVersion;
currentDateData s.Tables[0].Rows.Add(newRo w);

this.dbAdapter. InsertCommand = new OleDbCommand("I NSERT
INTO FailureControl (ControlDate, ControlVersion) VALUES('" +
currentDate + "', " + iVersion +")", this.dbConnecti on);
this.dbAdapter. Update(currentD ateDatas);

int iNewIndex = currentDateData s.Tables[0].Rows.Count - 1;
newRow = currentDateData s.Tables[0].Rows[iNewIndex];
iIndex = (int) newRow["IDFailureContr ol"];
}
finally
{
this.dbConnecti on.Close();
}

return iIndex;
}

Thanks and regards
Dec 31 '05 #1
6 14897
Marcel,

A first thing I would like to mention has to do with the use of Commands
(in your case OleDbCommand):
- It is much safer to work with command-parameters instead of building
your SQL-string. So create an OleDbCommand and set the
CommandTextProp erty to: "INSERT INTO FailureControl (ControlDate,
ControlVersion) VALUES(?, ?)"
then add the OleDbParameters to the command. Check
http://msdn.microsoft.com/library/de...classtopic.asp
for more information.

Then, to receive the ID of the last inserted row, the best solution
depends on the database-system you are using. Post some more information
please. I then will try to solve you whole problem.

Greetz,
Dries

Marcel Hug wrote:
Hi all !
I have a table in my database, which has 3 attributes. IDFailureContro l,
ControlDate and ControlVersion.

In the following function I test, if the date of today allready exists.
Then I would like to write the new ControlDate or Version into the
database. First i update the dataset, then i create a Insertcommand and
call the update-methode. All datas are in the database, but....

1.) If I only use the InsertCommand, without updating the dataset, the
datas would not be inserted to the database....?

2.) At the end I try to get the new created IDFailureContro l
(autoIncrement) , but it does not exist. Why ? how can I get this ID ?
here my code:

public int WriteControlDat e()
{
DateTime currentDate = DateTime.Today;
DataSet currentDateData s = new DataSet();
int iVersion = 0;
int iIndex = 0;

try
{
this.dbConnecti on.Open();

this.dbAdapter. SelectCommand = new OleDbCommand("S ELECT *
FROM FailureControl ORDER BY IDFailureContro l", this.dbConnecti on);
this.dbAdapter. Fill(currentDat eDatas);

if(currentDateD atas.Tables.Cou nt != 0)
{
int iLastRowIndex = currentDateData s.Tables[0].Rows.Count
- 1;
DataRow lastRow =
currentDateData s.Tables[0].Rows[iLastRowIndex];
DateTime lastControlDate = (DateTime)
lastRow["ControlDat e"];

if(lastControlD ate.Equals(curr entDate) == true)
{
iVersion = (int) lastRow["ControlVersion "];
iVersion++;
}
}

DataRow newRow = currentDateData s.Tables[0].NewRow();
newRow["ControlDat e"] = currentDate;
newRow["ControlVersion "] = iVersion;
currentDateData s.Tables[0].Rows.Add(newRo w);

this.dbAdapter. InsertCommand = new OleDbCommand("I NSERT INTO
FailureControl (ControlDate, ControlVersion) VALUES('" + currentDate +
"', " + iVersion +")", this.dbConnecti on);
this.dbAdapter. Update(currentD ateDatas);

int iNewIndex = currentDateData s.Tables[0].Rows.Count - 1;
newRow = currentDateData s.Tables[0].Rows[iNewIndex];
iIndex = (int) newRow["IDFailureContr ol"];
}
finally
{
this.dbConnecti on.Close();
}

return iIndex;
}

Thanks and regards

Dec 31 '05 #2
Hi Dries !
A first thing I would like to mention has to do with the use of Commands
(in your case OleDbCommand):
- It is much safer to work with command-parameters instead of building
your SQL-string. So create an OleDbCommand and set the
CommandTextProp erty to: "INSERT INTO FailureControl (ControlDate,
ControlVersion) VALUES(?, ?)"
then add the OleDbParameters to the command. Check
http://msdn.microsoft.com/library/de...classtopic.asp
for more information.
I have seen this solution, but I think it is a little bit confusing. Why
should I not use the popular and standartized SQL-Statements. Why
something new ?
Then, to receive the ID of the last inserted row, the best solution
depends on the database-system you are using. Post some more information
please. I then will try to solve you whole problem.


I'm using a simple MS Access 2000 database. The ID is incremented and a
primary key.

I have a new question:
I have datas in a dataset. I would like to save them in a new table
(just created). Do I have to run trought all recordsets with an Insert
into statement ?

Regards
Dec 31 '05 #3
Marcel,
I have seen this solution, but I think it is a little bit confusing. Why
should I not use the popular and standartized SQL-Statements. Why
something new ?

In my humble opinion, it is just easier to work with and it is less
error-sensitive.
Then, to receive the ID of the last inserted row, the best solution
depends on the database-system you are using. Post some more
information please. I then will try to solve you whole problem.


The best solution is to catch the OnRowUpdated event of the
OleDbDataAdapte r. You can then chech if the action was an Insert action
and if it was you can execute the "SELECT @@IDENTITY"-command to get the
last ID value. More information:
http://msdn.microsoft.com/library/de...mberValues.asp

I hope that this will be enough to solve the whole problem. If not, I am
at your disposal.

About your last question, putting data from a dataset into a newly
created table (I suggest you mean a table in a database and not an
ADO.NET DataTable)
When you are using an OleDbDataAdapte r you can use the Update method.
This methods accepts DataSet as well as DataTable as a parameter. So you
can just insert all data from whatever DataTable with a single call to
OleDbDataAdapte r.Fill. Be carefull with columnnames which can be
different in your database and DataTable. If this is the case, complete
the TableMappings of your Commands (see msdn-docs)

greetz,
Dries
Dec 31 '05 #4
Hi Dries !

Thanks for help
About your last question, putting data from a dataset into a newly
created table (I suggest you mean a table in a database and not an
ADO.NET DataTable)
When you are using an OleDbDataAdapte r you can use the Update method.
This methods accepts DataSet as well as DataTable as a parameter. So you
can just insert all data from whatever DataTable with a single call to
OleDbDataAdapte r.Fill. Be carefull with columnnames which can be
different in your database and DataTable. If this is the case, complete
the TableMappings of your Commands (see msdn-docs)


In my DataSet are more attributes (columns) then in the new table of the
database (access). I tries the following Mappings:

OleDbCommand dbCommand = new OleDbCommand("I NSERT INTO " +
strNewBackupTab le + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnecti on);
this.dbAdapter. InsertCommand = dbCommand;
this.dbAdapter. TableMappings.A dd("ENTRY", "Entry");
this.dbAdapter. TableMappings.A dd("DATEMAIN", "DateMain") ;
this.dbAdapter. TableMappings.A dd("Issued", "Issued");
this.dbAdapter. TableMappings.A dd("LASTUPDT", "LastUpdt") ;
this.dbAdapter. TableMappings.A dd("Modified", "Modified") ;
this.dbAdapter. TableMappings.A dd("VERSION", "Version");
this.dbAdapter. TableMappings.A dd("VersionText ", "VersionTex t");
this.dbAdapter. TableMappings.A dd("VSTATUS", "VSTATUS");
this.dbAdapter. Update(backupDa taSet);

But it does not work. I'm a little bit confused! In the Online MSDN is
the following sentence:

The mapping links the names of columns in the source with those in the
dataset table. For example, information from a column called au_id in
the data source might belong in a column called author_id_numbe r in the
dataset table.

Is the TableMappings for the columns- or the table names ? Because of
the body of the .Add function ???

Thanks !
Dec 31 '05 #5
Marcel,

Excuse me, I caused your confusion...
OleDbCommand dbCommand = new OleDbCommand("I NSERT INTO " +
strNewBackupTab le + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnecti on);
this.dbAdapter. InsertCommand = dbCommand;
this.dbAdapter. TableMappings.A dd("ENTRY", "Entry");
this.dbAdapter. TableMappings.A dd("DATEMAIN", "DateMain") ;
this.dbAdapter. TableMappings.A dd("Issued", "Issued");
this.dbAdapter. TableMappings.A dd("LASTUPDT", "LastUpdt") ;
this.dbAdapter. TableMappings.A dd("Modified", "Modified") ;
this.dbAdapter. TableMappings.A dd("VERSION", "Version");
this.dbAdapter. TableMappings.A dd("VersionText ", "VersionTex t");
this.dbAdapter. TableMappings.A dd("VSTATUS", "VSTATUS");
this.dbAdapter. Update(backupDa taSet);

But it does not work. I'm a little bit confused! In the Online MSDN is
the following sentence:

The mapping links the names of columns in the source with those in the
dataset table. For example, information from a column called au_id in
the data source might belong in a column called author_id_numbe r in the
dataset table.

Is the TableMappings for the columns- or the table names ? Because of
the body of the .Add function ???


You want to insert data from an ADO.NET DataTable into a table in a
Access database. The best way to do so is, like you already know, using
an OleDbDataAdapte r.
But the problem you are having here are the names of the columns and the
tables.
Take e.g. that your access-table is called 'BackupTable' but your
ADO.NET-datatabel is called 'Table1'; in this case you will have to user
the TableMappings property of the dataadapter.
If you want to map column-names, you have to use an OleDbCommand, which
you already have, and add parameters. These parameters have a property
called SourceColumn which refers to the name of the column in the
ADO.NET-datatable.

So, if you want to insert a value in the 'column1'-column of your
accestable, from a column called 'first_column' in your ADO.NET-table
you have to do the following

OleDbCommand command = new OleDbCommand("I NSERT INTO [add tablename of
access-db] (column1) VALUES (?)",this.dbcon nection);
command.Paramet ers.Add("column 1",[OleDbType of access column],[size of
the acces column],"first_column" );

this command can be used as the insertcommand of the dataadapter.

if you want to play safe, you can use the ADO.NET datatable as parameter
for the dataadapter.Fil l-method. This way you do not have to think about
mapping the tablename as there is only one table with data to pick data
from.

I hope I have been able to take away the confusion I caused.

greetz,
Dries
Dec 31 '05 #6
Hi Dries !
You want to insert data from an ADO.NET DataTable into a table in a
Access database. The best way to do so is, like you already know, using
an OleDbDataAdapte r.
But the problem you are having here are the names of the columns and the
tables.
Take e.g. that your access-table is called 'BackupTable' but your
ADO.NET-datatabel is called 'Table1'; in this case you will have to user
the TableMappings property of the dataadapter.
If you want to map column-names, you have to use an OleDbCommand, which
you already have, and add parameters. These parameters have a property
called SourceColumn which refers to the name of the column in the
ADO.NET-datatable.
Ahh Ok thanks...I'm Sorry, i did not find this information in the net

So, if you want to insert a value in the 'column1'-column of your
accestable, from a column called 'first_column' in your ADO.NET-table
you have to do the following

OleDbCommand command = new OleDbCommand("I NSERT INTO [add tablename of
access-db] (column1) VALUES (?)",this.dbcon nection);
command.Paramet ers.Add("column 1",[OleDbType of access column],[size of
the acces column],"first_column" );

this command can be used as the insertcommand of the dataadapter.

if you want to play safe, you can use the ADO.NET datatable as parameter
for the dataadapter.Fil l-method. This way you do not have to think about
mapping the tablename as there is only one table with data to pick data
from.

I hope I have been able to take away the confusion I caused.


Yes you have, but it does not work with my following code.
Could it be a problem, that the DataSet has much more attributes then
the new table ? In my oppinion it should not be a problem because of the
InsertCommand.. .I tried fill and update !!! nothing is working...
I'm tired of trying to get this data in the database. I will try again
tomorrow.

Thanks for yor help!
Happy New Year !

Here my code:

public void CreateNewBackup (DataSet backupDataSet, BackupTable backupTable)
{
try
{
string strNewBackupTab le = this.CreateNewB ackupTable(back upTable);

if(this.dbConne ction.State == ConnectionState .Closed)
{
this.dbConnecti on.Open();
}

OleDbCommand dbCommand = new OleDbCommand("I NSERT INTO " +
strNewBackupTab le + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnecti on);
dbCommand.Param eters.Add("Entr y", "ENTRY");
dbCommand.Param eters.Add("Date Main", "DATEMAIN") ;
dbCommand.Param eters.Add("Issu ed", "Issued");
dbCommand.Param eters.Add("Last Updt", "LASTUPDT") ;
dbCommand.Param eters.Add("Modi fied", "Modified") ;
dbCommand.Param eters.Add("Vers ion", "VERSION");
dbCommand.Param eters.Add("Vers ionText", "VersionTex t");
dbCommand.Param eters.Add("VSTA TUS", "VSTATUS");

this.dbAdapter. InsertCommand = dbCommand;
this.dbAdapter. TableMappings.A dd(strNewBackup Table,
backupDataSet.T ables[0].TableName);
this.dbAdapter. Fill(backupData Set);
}
finally
{
this.dbConnecti on.Close();
}
}
Dec 31 '05 #7

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

Similar topics

4
1594
by: Chris Mayers | last post by:
Hi, Hope someone can explain this... OK, here is the simplest subset of my code that shows the problem: I have a C# Method: Private void UpdateDataTable(DataTable myDT) {
16
17002
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums must be UPDATED, if not, they must be INSERTED. Logically then, I would like to SELECT * FROM <TABLE> WHERE ....<Values entered here>, and then IF FOUND UPDATE <TABLE> SET .... <Values entered here> ELSE INSERT INTO <TABLE> VALUES <Values...
1
5079
by: Bennett Haselton | last post by:
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);...
9
5268
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
1928
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)
0
5806
by: M. David Johnson | last post by:
I cannot get my OleDbDataAdapter to update my database table from my local dataset table. The Knowledge Base doesn't seem to help - see item 10 below. I have a Microsoft Access 2000 database which indexes computer magazine articles for personal reference. I am developing a Visual Basic.NET program whose sole purpose is to enter new records into the database. No updates to existing entries, no deletions, and no display
6
1852
by: tom c | last post by:
I create 2 data OleDbDataAdapters, one with the wizard, and one in code. I know the adapter created in code is OK because I use it to fill a data table. However, when I try to use the same SQL insert statement in the two adapters, the adapter created with the wizard works fine, but the adapter created in code gives me an error "Object reference not set to an instance of an object". The code is below. What am I doing wrong? ...
1
1589
by: explode | last post by:
I made a oledbdataadapter with this code Public Sub Novo(ByVal nova1 As String, ByVal nova2 As String) Dim i As Integer Dim nova As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter Dim veza As OleDb.OleDbConnection = New OleDb.OleDbConnection(Global.Diplomski1.My.MySettings.Default.Studenti1Connection) Dim tableMapping As System.Data.Common.DataTableMapping = New System.Data.Common.DataTableMapping("Marko", "Table1")
2
2921
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."...
0
8047
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8198
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
8376
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
6975
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
6044
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5503
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2515
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
1
1636
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1372
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.