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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Marcel Hug

    OleDBDataAdapter => 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
  • Dries

    #2
    Re: OleDBDataAdapte r => Insert and Update of data values in a Database

    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

    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:[color=blue]
    > 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[/color]

    Comment

    • Marcel Hug

      #3
      Re: OleDBDataAdapte r => Insert and Update of data values in a Database

      Hi Dries !
      [color=blue]
      > 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.[/color]

      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 ?
      [color=blue]
      > 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.[/color]

      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

      Comment

      • Dries

        #4
        Re: OleDBDataAdapte r => Insert and Update of data values in a Database

        Marcel,
        [color=blue]
        > 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 ?
        >[/color]
        In my humble opinion, it is just easier to work with and it is less
        error-sensitive.
        [color=blue][color=green]
        >> 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.[/color][/color]

        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:


        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

        Comment

        • Marcel Hug

          #5
          Re: OleDBDataAdapte r => Insert and Update of data values in a Database

          Hi Dries !

          Thanks for help
          [color=blue]
          > 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)[/color]

          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 !

          Comment

          • Dries

            #6
            Re: OleDBDataAdapte r => Insert and Update of data values in a Database

            Marcel,

            Excuse me, I caused your confusion...
            [color=blue]
            > 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 ???[/color]

            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

            Comment

            • Marcel Hug

              #7
              Re: OleDBDataAdapte r => Insert and Update of data values in a Database

              Hi Dries !
              [color=blue]
              > 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.[/color]

              Ahh Ok thanks...I'm Sorry, i did not find this information in the net

              [color=blue]
              > 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.[/color]

              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();
              }
              }

              Comment

              Working...