ncapsulating data update logic in stored procedures is an excellent way to improve the manageability, scalability, and security of your database-driven applications. There are many advantages to incorporating stored procedures into your application logic including:
- Shared application logic among various client applications
- Faster execution
- Reduced network traffic
- Improved database security
This article will show you how to use stored procedures in conjunction with the SqlDataAdapter in order to fill and update data contained in a DataSet.
Creating a Stored Procedure
Creating a stored procedure is a fairly straightforward process which you can complete inside the Visual Studio .NET IDE. Open Visual Studio .NET and navigate to the Pubs database node in the Server Explorer window and expand the node. You should see a Stored Procedures node (see Figure 1). Right-click on the Stored Procedures node to launch a popup menu. Select the option to create a new stored procedure.
![]() |
Fill a DataSet using a Stored Procedure In order to fill a DataSet with the publisher information, you can use a SqlDataAdapter as a broker between the SQL Server and the DataSet. The Fill method of the SqlDataAdapter retrieves the data from the database and populates the DataSet. Before you can execute the Fill method of the SqlDataAdapter, you must execute its SelectCommand property to a valid SqlCommand object. This SelectCommand is responsible for executing the T-SQL statement that returns the result set, which in turn fills the DataSet object. In order to demonstrate how to execute a stored procedure to fill a DataSet, create a new Windows Application project in Visual Studio. Add a class to the project and rename it Publishers. Add an Imports statement above the class definition to import the SqlClient namespace. Declare a private, class-level instance of each of the following classes: SqlConnection, SqlDataAdapter, SqlCommand, and DataSet.
Create a class constructor (Sub New) In the body of the constructor, instantiate the Connection object and pass in the connection string information. Instantiate the SELECT command and set the Connection, CommandType, and CommandText properties. Instantiate the DataAdapter and set its SelectCommand property to the cmdSelPubInfo object. Finally, instantiate the DataSet object, which will hold the result set returned from the database.
Create a function procedure called GetPubInfo in the class that takes no input parameters and returns a DataSet to the caller. In the body of the function, use the Fill method of the DataAdapter to fill the DataSet, then return it to the caller.
The Fill method of the DataAdapter will implicitly open the connection if it is closed and close it after the data is retrieved. If you explicitly open the connection, however, the DataAdapter will not close it. To test the method, place a DataGrid on Form1. Switch to the Code Editor window and declare a private class level instance of the Publishers class and the DataSet class after the Inherits statement.
In the Forms constructor code, instantiate a new instance of the Publishers class. Set dsPubInfo to the DataSet returned by calling the GetPubInfo method of the Publishers class. Set the DataSource property of the DataGrid to the first (and only) table in the dsPubInfo tables collection.
Run the application in the debugger and verify that the results are displayed in the grid. Update Data with a Stored Procedure The SqlParameter class encapsulates properties and methods for working with parameters. The SqlParameter class includes properties such as the ParameterName, SqlDBType, Direction, Size, Value, SourceColumn, and SourceVersion. The ParameterName, SqlDBType, Direction, and Size properties are set to match the parameter definition in the stored procedure. For example, the following code creates a parameter object that matches the @pub_id parameter in the up_UpdatePubInfo stored procedure created previously.
In this case, an overloaded constructor of the SqlParameter class sets the appropriate properties. Although the Direction property has not been explicitly set, Input is the default value. If the parameter direction is InputOutput, Output, or ReturnValue, you must explicitly set the direction. For example, the following code explicitly sets the Direction property of a SqlParameter object. The SourceColumn property maps a DataColumn from the DataTable passed in when you call the Update method of the SqlDataAdapter object. This mapping allows the implicit loading of the SqlParameter’s Value property from the DataTable during updates. If you do not set the SourceColumn parameter, you must explicitly set the Value property of the SqlParameter object. The SourceVersion property defaults to a value of Current, which is the current value of the field in the DataRow and is the value that you intend to update in your database. You can also set the SourceVersion of a SqlParameter object to a value of Original, which is the value of the field when the DataTable was originally loaded from the database. Passing both of these values to a stored procedure allows for concurrency checking before the data update takes place. The following stored procedure uses the original value to check if another user has changed the data before it performs an update. In order to execute this stored procedure, you define an @Original_pub_name SqlParameter object that uses the Original value of the field as its SourceVersion.
Once you’ve defined a SqlParameter object for each parameter identified in the stored procedure, you can add the SqlParameter objects to the Parameters collection of the SqlCommand object responsible for executing the stored procedure. The following code demonstrates adding a SqlParameter object to the Parameters collection.
As an alternative, the overloaded Add method allows you to create the SqlParameter object and add it to the collection in one step.
In order to demonstrate how to use a SqlDataAdapter object in conjunction with a stored procedure to update data, open the Windows Application project you created earlier. Using the Server Explorer window, create the up_UpdPubName stored procedure in the Pubs database. Open the Publishers class in the Code Editor and add the following class-level declaration to create a SqlCommand object.
In the body of the class constructor, add code to instantiate the update command and set the Connection, CommandType, and CommandText properties.
Next, define and add the necessary update parameters to the Parameters collection.
Add code after the DataAdapter instantiation to set the UpdateCommand property of the DataAdapter to the cmdUpdPubInfo object.
Create a subprocedure called UpdatePubInfo that takes a DataSet object as an input parameter. In the body of the function, call the Update method of the DataAdapter object and pass in the DataSet. Add a button to Form1 and add code to the button’s Update event that calls the UpdatePubInfo method of objPublisher. First, check if the DataSet has changes by calling the HasChanges method. If there are changes, filter the dsPublisher and pass only the changed rows by calling the GetChanges method of the DataSet. Run the application in Debug mode. Make changes to the pub_name and click the Update button. Stop the application. Right-click on the publisher table node in the Server Explorer window and choose Retrieve Data from Table. Verify that the changes updated the database. Now that you are familiar with using a stored procedure to implement updating data through the SqlDataApapter, you can implement data inserts and deletes in a similar manner. This will be an exercise left for the reader. The solution code for this article contains sample code that demonstrates inserts and updates using the SqlDataAdapter. This article demonstrated how to use the SqlDataAdapter class and its parameters to update a database. You also read how to use the SqlDataAdapter in conjunction with stored procedures to propagate data changes in a disconnected DataSet back to the database. Encapsulating data update logic in stored procedures is an excellent way to improve the manageability, scalability, and security of your database-driven applications. One area this article does not address is data concurrency. Dealing with data concurrency is vital in a disconnected scenario.
Share the Post:
![]() ![]() Data Observability Explained
June 8, 2023
Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the ![]() ![]() Logitech G502 Software: Optimize and Customize Your Gear
June 8, 2023
One of the most significant surges of the 21st century is gaming. Gaming is more popular than ever before thanks to innovative new consoles, high-tech PC setups, mobile gaming improvements, ![]() ![]() Different Types of Data Models Explained with Examples
June 7, 2023
In the modern world, data is everything and everywhere. With so much access to technology, data has become a valuable resource for any business. Albeit a complex one. Data is ![]() ![]() Revolutionizing Search: A Glimpse Into Google’s Generative Experience
June 6, 2023
Google is revolutionizing the search experience as we know it with its latest generative experience. No longer will you be bound by the limitations of traditional keyword searching. Now, you ![]() ![]() 10 Productivity Hacks to Supercharge Your Business in 2023
June 5, 2023
Picture this: your team working seamlessly, completing tasks efficiently, and achieving goals with ease. Sounds like too good to be true? Not at all! With our productivity hacks, you can ![]() ![]() GM Creates Open Source uProtocol and Invites Automakers to Adopt It: Revolutionizing Automotive Software Development.
June 2, 2023
General Motors (GM) recently announced its entry into the Eclipse Foundation. The Eclipse Foundation is a prominent open-source software foundation. In addition, GMC announced its contribution of “uProtocol” to facilitate ![]() ![]() What is Metadata?
June 1, 2023
What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular ![]() ![]() What We Should Expect from Cell Phone Tech in the Near Future
May 31, 2023
The earliest cell phones included boxy designs full of buttons and antennas, and they only made calls. Needless to say, we’ve come a long way from those classic brick phones ![]() ![]() The Best Mechanical Keyboards For Programmers: Where To Find Them
May 29, 2023
When it comes to programming, a good mechanical keyboard can make all the difference. Naturally, you would want one of the best mechanical keyboards for programmers. But with so many ![]() ![]() The Digital Panopticon: Is Big Brother Always Watching Us Online?
May 26, 2023
In the age of digital transformation, the internet has become a ubiquitous part of our lives. From socializing, shopping, and learning to more sensitive activities such as banking and healthcare, ![]() ![]() Embracing Change: How AI Is Revolutionizing the Developer’s Role
May 25, 2023
The world of software development is changing drastically with the introduction of Artificial Intelligence and Machine Learning technologies. In the past, software developers were in charge of the entire development ![]() ![]() The Benefits of Using XDR Solutions
May 24, 2023
Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved |