473,323 Members | 1,537 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,323 software developers and data experts.

OleDBDataAdapter => Insert and Update of data values in a Database

Hi all !
I have a table in my database, which has 3 attributes. IDFailureControl,
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 IDFailureControl
(autoIncrement), but it does not exist. Why ? how can I get this ID ?
here my code:

public int WriteControlDate()
{
DateTime currentDate = DateTime.Today;
DataSet currentDateDatas = new DataSet();
int iVersion = 0;
int iIndex = 0;

try
{
this.dbConnection.Open();

this.dbAdapter.SelectCommand = new OleDbCommand("SELECT *
FROM FailureControl ORDER BY IDFailureControl", this.dbConnection);
this.dbAdapter.Fill(currentDateDatas);

if(currentDateDatas.Tables.Count != 0)
{
int iLastRowIndex =
currentDateDatas.Tables[0].Rows.Count - 1;
DataRow lastRow =
currentDateDatas.Tables[0].Rows[iLastRowIndex];
DateTime lastControlDate = (DateTime)
lastRow["ControlDate"];

if(lastControlDate.Equals(currentDate) == true)
{
iVersion = (int) lastRow["ControlVersion"];
iVersion++;
}
}

DataRow newRow = currentDateDatas.Tables[0].NewRow();
newRow["ControlDate"] = currentDate;
newRow["ControlVersion"] = iVersion;
currentDateDatas.Tables[0].Rows.Add(newRow);

this.dbAdapter.InsertCommand = new OleDbCommand("INSERT
INTO FailureControl (ControlDate, ControlVersion) VALUES('" +
currentDate + "', " + iVersion +")", this.dbConnection);
this.dbAdapter.Update(currentDateDatas);

int iNewIndex = currentDateDatas.Tables[0].Rows.Count - 1;
newRow = currentDateDatas.Tables[0].Rows[iNewIndex];
iIndex = (int) newRow["IDFailureControl"];
}
finally
{
this.dbConnection.Close();
}

return iIndex;
}

Thanks and regards
Dec 31 '05 #1
6 14828
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
CommandTextProperty 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. IDFailureControl,
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 IDFailureControl
(autoIncrement), but it does not exist. Why ? how can I get this ID ?
here my code:

public int WriteControlDate()
{
DateTime currentDate = DateTime.Today;
DataSet currentDateDatas = new DataSet();
int iVersion = 0;
int iIndex = 0;

try
{
this.dbConnection.Open();

this.dbAdapter.SelectCommand = new OleDbCommand("SELECT *
FROM FailureControl ORDER BY IDFailureControl", this.dbConnection);
this.dbAdapter.Fill(currentDateDatas);

if(currentDateDatas.Tables.Count != 0)
{
int iLastRowIndex = currentDateDatas.Tables[0].Rows.Count
- 1;
DataRow lastRow =
currentDateDatas.Tables[0].Rows[iLastRowIndex];
DateTime lastControlDate = (DateTime)
lastRow["ControlDate"];

if(lastControlDate.Equals(currentDate) == true)
{
iVersion = (int) lastRow["ControlVersion"];
iVersion++;
}
}

DataRow newRow = currentDateDatas.Tables[0].NewRow();
newRow["ControlDate"] = currentDate;
newRow["ControlVersion"] = iVersion;
currentDateDatas.Tables[0].Rows.Add(newRow);

this.dbAdapter.InsertCommand = new OleDbCommand("INSERT INTO
FailureControl (ControlDate, ControlVersion) VALUES('" + currentDate +
"', " + iVersion +")", this.dbConnection);
this.dbAdapter.Update(currentDateDatas);

int iNewIndex = currentDateDatas.Tables[0].Rows.Count - 1;
newRow = currentDateDatas.Tables[0].Rows[iNewIndex];
iIndex = (int) newRow["IDFailureControl"];
}
finally
{
this.dbConnection.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
CommandTextProperty 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
OleDbDataAdapter. 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 OleDbDataAdapter 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
OleDbDataAdapter.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 OleDbDataAdapter 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
OleDbDataAdapter.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("INSERT INTO " +
strNewBackupTable + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnection);
this.dbAdapter.InsertCommand = dbCommand;
this.dbAdapter.TableMappings.Add("ENTRY", "Entry");
this.dbAdapter.TableMappings.Add("DATEMAIN", "DateMain");
this.dbAdapter.TableMappings.Add("Issued", "Issued");
this.dbAdapter.TableMappings.Add("LASTUPDT", "LastUpdt");
this.dbAdapter.TableMappings.Add("Modified", "Modified");
this.dbAdapter.TableMappings.Add("VERSION", "Version");
this.dbAdapter.TableMappings.Add("VersionText", "VersionText");
this.dbAdapter.TableMappings.Add("VSTATUS", "VSTATUS");
this.dbAdapter.Update(backupDataSet);

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_number 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("INSERT INTO " +
strNewBackupTable + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnection);
this.dbAdapter.InsertCommand = dbCommand;
this.dbAdapter.TableMappings.Add("ENTRY", "Entry");
this.dbAdapter.TableMappings.Add("DATEMAIN", "DateMain");
this.dbAdapter.TableMappings.Add("Issued", "Issued");
this.dbAdapter.TableMappings.Add("LASTUPDT", "LastUpdt");
this.dbAdapter.TableMappings.Add("Modified", "Modified");
this.dbAdapter.TableMappings.Add("VERSION", "Version");
this.dbAdapter.TableMappings.Add("VersionText", "VersionText");
this.dbAdapter.TableMappings.Add("VSTATUS", "VSTATUS");
this.dbAdapter.Update(backupDataSet);

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_number 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 OleDbDataAdapter.
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("INSERT INTO [add tablename of
access-db] (column1) VALUES (?)",this.dbconnection);
command.Parameters.Add("column1",[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.Fill-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 OleDbDataAdapter.
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("INSERT INTO [add tablename of
access-db] (column1) VALUES (?)",this.dbconnection);
command.Parameters.Add("column1",[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.Fill-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 strNewBackupTable = this.CreateNewBackupTable(backupTable);

if(this.dbConnection.State == ConnectionState.Closed)
{
this.dbConnection.Open();
}

OleDbCommand dbCommand = new OleDbCommand("INSERT INTO " +
strNewBackupTable + " (Entry, DateMain, Issued, LastUpdt, Modified,
Version, VersionText, VSTATUS) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
this.dbConnection);
dbCommand.Parameters.Add("Entry", "ENTRY");
dbCommand.Parameters.Add("DateMain", "DATEMAIN");
dbCommand.Parameters.Add("Issued", "Issued");
dbCommand.Parameters.Add("LastUpdt", "LASTUPDT");
dbCommand.Parameters.Add("Modified", "Modified");
dbCommand.Parameters.Add("Version", "VERSION");
dbCommand.Parameters.Add("VersionText", "VersionText");
dbCommand.Parameters.Add("VSTATUS", "VSTATUS");

this.dbAdapter.InsertCommand = dbCommand;
this.dbAdapter.TableMappings.Add(strNewBackupTable ,
backupDataSet.Tables[0].TableName);
this.dbAdapter.Fill(backupDataSet);
}
finally
{
this.dbConnection.Close();
}
}
Dec 31 '05 #7

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

Similar topics

4
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
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...
1
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: ...
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"...
0
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...
6
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...
1
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...
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.