Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. read & update using reader

read & update using reader

Scheduled Pinned Locked Moved Database
databasequestionsharepointtutorialannouncement
34 Posts 15 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Mycroft Holmes

    In this context a grid is a generic term for a collection control and with winforms I was always happy to bind a datatable to a datagirdview, the datatable is disconnected afterall. The cost of the datatable has always been irrelevant to the functionality that it brings. Then we were told to use services and I decided the UI should be silverlight so everything changed, now it's Oracle databases, WCF, observablecollections, viewmodels and xaml. Did I say I hate (relearning) Oracle.

    Never underestimate the power of human stupidity RAH

    P Offline
    P Offline
    PIEBALDconsult
    wrote on last edited by
    #21

    Mycroft Holmes wrote:

    (relearning) Oracle.

    But not in C with Pro*C I bet.

    1 Reply Last reply
    0
    • R RaviRanjanKr

      Mark Nischalke wrote:

      how does this answer the question?

      :doh: Ok its my fault but can you explain what extra I have to mention here.

      M Offline
      M Offline
      MDNadeemAkhter
      wrote on last edited by
      #22

      :-D

      1 Reply Last reply
      0
      • J Jassim Rahma

        I have the following to read from database: sql_connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString); sql_connection.Open(); sql_command = new MySqlCommand("sp_send_pending_sms", sql_connection); sql_command.CommandType = CommandType.StoredProcedure; sql_reader = sql_command.ExecuteReader(); after reading I want to update every record when send to set the field is_sent to True? how can i do this? do I have to create another reader in the middle? can you please guide.. Thanks

        B Offline
        B Offline
        Brady Kelly
        wrote on last edited by
        #23

        It is maybe neater to not use a reader, but rather a DataTable and a TableAdapter. Then you can loop through the table rows, update the is_sent on each row as you process it, and then call Update. Something like this:

        using (var ad = new SqlDataAdapter("sp\_send\_pending\_sms", ConfigurationManager.ConnectionStrings\["SQLdb"\].ConnectionString))
        {
            ad.SelectCommand.CommandType = CommandType.StoredProcedure;
            var dt = new DataTable();
            ad.Fill(dt);
        
            // blah blah blah. do your work.
            ad.AcceptChangesDuringUpdate = true;
            ad.Update(dt);
        }
        

        If the list is long, you may want to call Update every n rows, not just at the end.

        1 Reply Last reply
        0
        • J Jassim Rahma

          I have the following to read from database: sql_connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString); sql_connection.Open(); sql_command = new MySqlCommand("sp_send_pending_sms", sql_connection); sql_command.CommandType = CommandType.StoredProcedure; sql_reader = sql_command.ExecuteReader(); after reading I want to update every record when send to set the field is_sent to True? how can i do this? do I have to create another reader in the middle? can you please guide.. Thanks

          G Offline
          G Offline
          Gary Huck
          wrote on last edited by
          #24

          Yes, something like that is what you need. The ExecuteReader() method, as the name implies, is only for selecting (reading) data. p.s. Stored procedures are a great way to go!

          P 1 Reply Last reply
          0
          • P PIEBALDconsult

            If you use stored procedures (and you shouldn't), don't prefix the names with "sp"[^]. When I implement a system like that, sending email or whatever, I put a Status field in the table to indicate ( 0=New , 1=Sending , 2=Sent ). When I select the New rows, I also set the Status to Sending, then when I'm done I set the Sending rows to Sent. "UPDATE Email SET Status=1 WHERE Status=0 ; SELECT * FROM Email WHERE Status=1" Send the emails. "UPDATE Email SET Status=2 WHERE Status=1"

            G Offline
            G Offline
            Gary Huck
            wrote on last edited by
            #25

            Tell us why one should NOT use stored procedures, as you state.

            1 Reply Last reply
            0
            • P PIEBALDconsult

              I have never understood the reason so many devs use the DataAdapter and load a whole butt-load of data at once when they don't use it all at once. Certainly, when I want to load a ListBox or something, I use a DataTable (loaded straight from a DataReader), but mostly I use only one record at a time -- to export or copy somewhere or update something. For what I do, I doubt the connection stays open significantly longer, but it sure saves on RAM and class instantiations. Bear in mind that I generally write Windows Services that cycle every ten to fifteen seconds, and not generally GUI apps that spend a lot of time just sitting there displaying a bunch of out-dated data. And when I do write a WinForms app that displays a butt-load of data, I often use a Service to create an (XML) export that the clients read, rather than have all the clients constantly clambering for database connections.

              F Offline
              F Offline
              Fabio Franco
              wrote on last edited by
              #26

              PIEBALDconsult wrote:

              I have never understood the reason so many devs use the DataAdapter and load a whole butt-load of data at once when they don't use it all at once.

              When you know there will never be too much data and that it will not have impact on system resources and when you want to work with data in a disconected state. There are good uses for both approaches, that's why they exist. Beeing wise to use them where they fit is another story, can't speak for anyone.

              1 Reply Last reply
              0
              • J Jassim Rahma

                I have the following to read from database: sql_connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString); sql_connection.Open(); sql_command = new MySqlCommand("sp_send_pending_sms", sql_connection); sql_command.CommandType = CommandType.StoredProcedure; sql_reader = sql_command.ExecuteReader(); after reading I want to update every record when send to set the field is_sent to True? how can i do this? do I have to create another reader in the middle? can you please guide.. Thanks

                S Offline
                S Offline
                Spectre_001
                wrote on last edited by
                #27

                You can not update through a DataReader. It retreives a read-only, forward-only stream of data one record at a time. If I read your question correctly, you are doing some processing on each record after reading, then need to set a flag in the database to indicate that record has been processed. You will need a second connection and comand object for this. You can't use the same connection/command as the DataReader because it keeps it's connection open internally throughout it's lifetime. The best way to accomplish this will vary slightly depending on how many records you expect to process and whether the processing will run a long time (cumulative). For a relatively short run: 1. Open SQLConnection for updating and attach to SQLCommand 2. Read next record from DataReader 3. Perform needed processing 4. Generate update SQL for current record 5. Use SQLCommand to run update SQL 6. Repeat steps 2 - 5 until last record has been processed and updated 7. Close and destroy update SQLConnection/SQLCommand For a long run: 1. Create SQLConnection for updating and attach to SQLCommand 2. Read next record from DataReader 3. Perform needed processing 4. Generate update SQL for current record 5. Open SQLConnection for update 6. Use SQLCommand to run update SQL 7. Close SQLConnection 8. Repeat 2 - 7 until last record has been processed and updated 9. Close and destroy update SQLConnection/SQLCommand Hope this answers your question and helps out.

                Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                P 1 Reply Last reply
                0
                • M Mycroft Holmes

                  PIEBALDconsult wrote:

                  If you use stored procedures (and you shouldn't),

                  Do you want to clarify that statement.

                  Never underestimate the power of human stupidity RAH

                  M Offline
                  M Offline
                  Miroslav Bucko
                  wrote on last edited by
                  #28

                  That article is from 2003. And yeah, i'm wondering too, why?

                  M 1 Reply Last reply
                  0
                  • J Jassim Rahma

                    I have the following to read from database: sql_connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString); sql_connection.Open(); sql_command = new MySqlCommand("sp_send_pending_sms", sql_connection); sql_command.CommandType = CommandType.StoredProcedure; sql_reader = sql_command.ExecuteReader(); after reading I want to update every record when send to set the field is_sent to True? how can i do this? do I have to create another reader in the middle? can you please guide.. Thanks

                    J Offline
                    J Offline
                    Jason Christian
                    wrote on last edited by
                    #29

                    Short answer - You can't. It is a data READER - not an updater. It's not like opening a recordset in VB6. You need to ExecuteSQL with appropriate SQL to udpate the records (i.e. UPDATE table SET field=value WHERE key=id). To do it the way you want it would better to use a DataSet or something a little more robust - plenty of info on MSDN.

                    1 Reply Last reply
                    0
                    • M Miroslav Bucko

                      That article is from 2003. And yeah, i'm wondering too, why?

                      M Offline
                      M Offline
                      Mycroft Holmes
                      wrote on last edited by
                      #30

                      Nothing fundamental has changed in databases since 2003 so the premise of the article is still very valid, I just don't agree with it.

                      Never underestimate the power of human stupidity RAH

                      1 Reply Last reply
                      0
                      • G Gary Huck

                        Yes, something like that is what you need. The ExecuteReader() method, as the name implies, is only for selecting (reading) data. p.s. Stored procedures are a great way to go!

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #31

                        GamleKoder wrote:

                        is only for selecting (reading) data.

                        No it isn't; it can execute any SQL statement (even a list of them if the particular database engine supports it) and it underlies all the other ADO.net data manipulation methody, so you're using it whether you know it or not.

                        1 Reply Last reply
                        0
                        • S Spectre_001

                          You can not update through a DataReader. It retreives a read-only, forward-only stream of data one record at a time. If I read your question correctly, you are doing some processing on each record after reading, then need to set a flag in the database to indicate that record has been processed. You will need a second connection and comand object for this. You can't use the same connection/command as the DataReader because it keeps it's connection open internally throughout it's lifetime. The best way to accomplish this will vary slightly depending on how many records you expect to process and whether the processing will run a long time (cumulative). For a relatively short run: 1. Open SQLConnection for updating and attach to SQLCommand 2. Read next record from DataReader 3. Perform needed processing 4. Generate update SQL for current record 5. Use SQLCommand to run update SQL 6. Repeat steps 2 - 5 until last record has been processed and updated 7. Close and destroy update SQLConnection/SQLCommand For a long run: 1. Create SQLConnection for updating and attach to SQLCommand 2. Read next record from DataReader 3. Perform needed processing 4. Generate update SQL for current record 5. Open SQLConnection for update 6. Use SQLCommand to run update SQL 7. Close SQLConnection 8. Repeat 2 - 7 until last record has been processed and updated 9. Close and destroy update SQLConnection/SQLCommand Hope this answers your question and helps out.

                          Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                          P Offline
                          P Offline
                          PIEBALDconsult
                          wrote on last edited by
                          #32

                          Spectre_001 wrote:

                          You can not update through a DataReader

                          No, but you can through ExecuteReader. In your scenarios... generate a parameterized update command up front and then set the parameters for each row and execute -- no need to keep generating the same SQL statement.

                          S 1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            Spectre_001 wrote:

                            You can not update through a DataReader

                            No, but you can through ExecuteReader. In your scenarios... generate a parameterized update command up front and then set the parameters for each row and execute -- no need to keep generating the same SQL statement.

                            S Offline
                            S Offline
                            Spectre_001
                            wrote on last edited by
                            #33

                            That dosen't help if he needs to read, process, then update. :-D

                            Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                            1 Reply Last reply
                            0
                            • P PIEBALDconsult

                              If you use stored procedures (and you shouldn't), don't prefix the names with "sp"[^]. When I implement a system like that, sending email or whatever, I put a Status field in the table to indicate ( 0=New , 1=Sending , 2=Sent ). When I select the New rows, I also set the Status to Sending, then when I'm done I set the Sending rows to Sent. "UPDATE Email SET Status=1 WHERE Status=0 ; SELECT * FROM Email WHERE Status=1" Send the emails. "UPDATE Email SET Status=2 WHERE Status=1"

                              J Offline
                              J Offline
                              James Lonero
                              wrote on last edited by
                              #34

                              Using stored procedures, more of a good thing than using dynamic SQL? The article makes a good argument about changes legacy systems. The need to change the stored procedures will break code, or adding more stored procedures adds extra (duplicate) overhead. If just adding a new column to a table requires adding a new input parameter, we will need to add a new stored procedure to handle it. Of course, the old stored procedure can call the new stored procedure with a dummy argument for the new input value. On the other hand, using dynamic SQL may require revision to add the new parameter (where it is needed). The down side is that legacy code that uses the database will need to have its SQL updated. Not only will the new application making use of the "improved" database have the changes, but all of the older applications will need to change, if the new database is used with them. And, there is the possibility of SQL injection attacks, depending on how you store your SQL in your application. Updating Stored Procedures is akin to the old days of COM programming. There was a rule, at one time, that said we should not change a published interface, but make a new interface. This also was applied to the methods as well. And, a good programmer will do the least amount of work to get the job done efficiently. You must decide which method is best for you.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups