Working with MS Access Stored Procedures in vb.net. Part 1
BY
David Wasserman, MCP
2/27/2002
Article source code:. Msaccess_sp.zip Introduction In the more recent releases of Microsoft Access, great effort has gone into making this product a full-featured relational database system Stored procedures, a functionality usually associated with enterprise database systems such as SQL Server, can now be found in Access. Stored procedures in Access have been available since Access 2000 and are native to the Jet 4 Database Engine. If you're accustomed to using stored procedures in SQL Server, then you'll be right at home with how they 're used in Access. However there are some limitations to keep in mind. I'll discuss those later on. This article will be broken down into two parts. Part one will describe in detail how to create stored procedures in Access using ADO. NET and Visual Basic.NET. Part two will demonstrate how to utilize the stored procedures created in part one by assembling a data access tier that can be modelled and used in your own applications. The code in this article h as been tested using Access 2002, although it should also work with Access 2000. How do stored procedures work in Access? Unlike other objects in Access, stored procedures have no interface and can not be created or run through the Access User Interface. The way to Get Theim Into Your Database Is To Simply Code Them. I'll Show How Tat '
s done in ADO.NET. When a stored procedure is added to an Access Database, the Jet Engine reworks the stored procedure syntax into a query object. To an Access developer this may sound like unnecessary work to code a query. However, it does have its advantages. Consider an application that has to break out into different versions when maintaining both an Access Database and a SQL Server Database. Using stored procedures will make it easier to write the code for the database tier of the application as the program will change very little between the different versions. Creating Stored Procedures to demonstrate, I'll first show how to create the SQL statements to create stored procedures. At the end of the article I'll show the entire code needed to run these statements against the database ............................................................................................................... Ch row in the table. To create the stocking sql statement against the database: "create proc procproductslist as select * from products;"
The statement:.. "CREATE PROC procCustomerList" is the part that actually creates the stored procedure The part following "AS" can be any valid SQL Statement Often in a stored procedure you'll want to pass a value to be used in the query That You May Want To Delete A Record, ON A Particular ProductId. The Following Stored Procedure Shows How To Do Just That:
"Create Proc ProcproductsDeleteItem (InproductSid Long" & _ "AS Delete from Products Where Productsid = InproductsId;"
On the first line, notice the parenthesis right after the CREATE PROC declaration. There is a parameter defined as a Long value. This is where you add the variable to delete the record in question. The next two statements show how to create an add and an update stored procedure for the Products table respectively Note that not all fields are included for the sake of brevity:. "CREATE PROC procProductsAddItem (inProductName VARCHAR (40)," & _ "inSupplierID LONG, inCategoryID LONG)" & _ "AS INSERT INTO Products (ProductName, Supplierid, CategoryId "& _" VALUES (InproductName, InsupplierID, IncategoryID); "
"CREATE PROC procProductsUpdateItem (inProductID LONG," & _ "inProductName VARCHAR (40))" & _ "AS UPDATE Products SET ProductName = inProductName" & _ "WHERE ProductID = inProductID;"
.
Output parameters can not be used. Do not use the @ character. The @ character is often used in Transact SQL (SQL Server), where it represents a local variable. Access does not always convert this character and will sometimes leave it out. This can cause esoteric bugs which can lead to premature hair loss. Temporary tables are not available in Access. I suspect many of the options available in Transact SQL are not available in Access as it's not Transact SQL compatible. Conclusion Hopefully, this article has provided some guidance in a nearly undocumented area of Access and Jet not yet explored by most. For more information on how the ADO.NET code works in the CreateStoredProc subroutine, see Getting Started with ADO.NET by Gurneet Singh. The following is a complete listing Of All Code Presened in this article: imports system
Imports system.data
Imports system.data.oledb
Module Createsp
Sub main ()
ProductsProcs ()
End Sub
'Products Stored Procs To Be Added to the DB.
Sub productsprocs ()
DIM SSQL AS String
'Procproductslist - Retrieves Entire Table
SSQL = "Create Proc ProcproductSlist as Select * from Products;"
CreateStRedProc (SSQL)
'Procproductsdeetetem - returns the details (One Record) from the
'Jobtitle Table
SSQL = "CREATE PROC ProcproductsDeleteItem (@Productid long) AS" _
& "Delete from products where produter = @ProductId;"
CreateStRedProc (SSQL)
'Procproductsadditem - add one record to the jobtitle TABLE
SSQL = "CREATE PROC ProcproductsAdditem (InproductName Varchar (40)," _
& "Insupplierid Long, Incategoryid Long) AS Insert Into" _
& "Products (ProductName, Supplierid, CategoryId) Values" _ & "(InproductName, InsupplierID, CategoryId);"
CreateStRedProc (SSQL)
'ProcproductsupdateItem - Update One Record on The Jobtitle Table
SSQL = "Create Proc ProcproductsupdateItem (Inproductid long,"
& "InproductName VARCHAR (40)) AS Update Products Set" _
& "ProductName = InproductName Where ProductId = InproductId;"
CreateStRedProc (SSQL)
End Sub
'Execute The Creation of Stored Procedures
Sub CreateStoredProc (Byval SSQL AS String)
DIM CON AS OLEDBCONNECTION
DIM CMD AS Oledbcommand = New OLEDBCommand ()
DIM DA AS OLEDBDataAdapter
'Change Data Source to the location of northwind.mdb on Your Local
'System.
DIM sconstr as string = "provider = microsoft.jet.Oledb.4.0; data" _
& "Source = C: / Program Files / Microsoft" _
& "Office / Office10 / Samples / Northwind.mdb"
Con = New OLEDBCONNECTION (SCONSTR)
cmd.connection = con
cmd.commandtext = SSQL
Con.open ()
cmd.executenonquery ()
Con. close ()
End Sub
End Module Working with MS Access Stored Procedures in VB.NET Part 2 by David Wasserman, MCP 4/18/2002 Article source code:.. Msaccess_sp2.zipIntroductionWelcome to part two of Access Stored Procedures Part one described in detail how to create stored procedures in Access using ADO.NET and Visual Basic.NET. Part two will demonstrate how to utilize the stored procedures created in part one by assembling a Database Tier that can be modelled and used in your own applications. This article will describe in detail one implementation of a Database Tier for Visual Basic.NET.The main purpose of the Database Tier is to provide a gateway to the database via a class module. This class module would act as the glue between the database and the application. There are two main advantages to using a data tier to access your database. You will have the ability to modify your underlying database technology (moving from MS Access to SQL Server for instance) without affecting your application in a major w ay. You will also be placing a control layer between your application and the database allowing you to ensure that all data is properly "cleansed". The Database Tier in .NET applications would most likely consist of a class module keeping in line with proper object -oriented coding conventions Earlier versions of Visual Basic would employ a Standard Module to do the job.Database Tier -. CodeIt's now time to roll up our sleeves and get dirty with some code The first thing after adding an empty class declaration file is to. Pull in The Proper .NET Framework Libraries Listed Below.Imports SYSTEM
Imports system.data
Imports system.data.oledb
The System Library is standard for most applications, and I make it a habit to include it in almost all my code modules. The System.Data library is necessary for almost all database access applications. The System.Data.OleDb is used specifically for OLEDB . Database Providers to which Microsoft Access belongs to If we were using SQL Server we'd include the custom SQL provider System.Data.SqlClient.Then next line of code starts the definition of the Class: Public Class DBTier
Here We've Named The Class DBTier and Have Given It A Modifier of Public, Thus Making It Very Access from Other Code Modules. After the class is deflared:
Shared connectionString as string = _
"Provider = microsoft.jet.Oledb.4.0; data source = c: / program" _
& "Files / Microsoft Office / Office10 / Samples / Northwind.mdb"
Only one property is declared here as a string variable, connectionString. This variable holds the connection string for the Northwind Access Database. Declaring the variable as Shared defines it as "Class Variable". A class variable is associated with the class, not each object instantiated from the class. After the connection string declaration you'll find there are three subroutines and one function. The function returns a dataset with a listing of all products. It calls the stored procedure procProductsList, created in part one of this article.Next you'll find the three subroutines There is one for each stored procedure;. add, update and deletion of products They're all similarly structured;. each with a command, connection and required parameter (s) declared As a sample, let's. dissect the ProductsDeleteItem subroutine. After understanding how this subroutine works the others should be easy to digest.To start off the routine takes in one parameter, ProductID, which is an Integer re Presenting the product to be deleted.sub productsDeleteItem (Byval Productid AS Integer)
Next, All Variables Are Declared. One for the connection, command and a parameter to be passed into the stored procedure. This parameter is the produter to be deleted.
DIM CON AS OLEDBCONNECTION
DIM CMD AS Oledbcommand = New OLEDBCommand ()
DIM paramproductid as new oledbparameter ()
Command and connection Objects are initialized:
Con = New OLEDBConnection (Connectionstring)
cmd.connection = con
The paramProductID parameter properties are configured. Then the parameter is added to the command object. In this case the parameter name in the stored procedure is inProductID, it's an integer and the value is set to the ProductID passed into this subroutine.With paramProductID
.ParameterName = "inproductid"
.Oledbtype = oledbtype.integer
.Size = 4
.Value = productID
End with
cmd.parameters.add (paramproductid)
The Last Part Actually Calls The Stored ProCedure.
cmd.commandtext = "Execute ProcproductsDeleteItem"
Con.open ()
cmd.executenonquery ()
Con. close ()
Notice that the connection object only stays open long enough to carry out the stored procedure and then closes immediately. This reduces any possible contention.While the DBTier class included in this article clearly describes how to access the stored procedures, it would need some enhancements to become quality production code since no error handling has been added. There may also be the need to further enhance performance here.The downloaded source code associated with this article includes the DBTier.vb file along with some very basic forms to test the actual implementation of the class.In conclusion, I hope you have gained at least two things from these articles. One being that stored procedures are alive and well in Microsoft Access, although not without their limitations. The second thing to walk away with here is understanding the need TO BREAK DOWN An Application's Data Access INTO Separate Classes, Subroutines and Functions. This Makes Maintenance and Upgrades Much Easier To Implement.ntire dbtier.vb Source Code:
Imports system
Imports system.data
Imports system.data.oledb
'Functions and Subroutines for Executing Stored Procedures in Acup.Public Class DBTIER
'Change Data Source to the location of northwind.mdb on Your Local
'System.
Shared connectionString as string = _
"Provider = microsoft.jet.Oledb.4.0; data source = c: / program" _
& "Files / Microsoft Office / Office10 / Samples / Northwind.mdb"
'This function returns a DataSet Containing All Records in
'The products table.
Function ProductsList () AS Dataset
DIM CON AS OLEDBCONNECTION
DIM DA AS OLEDBDataAdapter
DIM DS AS Dataset
DIM SSQL AS String
SSQL = "Execute ProcproductsList"
Con = New OLEDBConnection (Connectionstring)
Da = New OLEDBDataAdapter (SSQL, CON)
DS = new dataset ()
Da.fill (DS, "Products")
Return DS
END FUNCTION
'This function add one record to the produter.
Sub ProductsAdditem (Byval Productname As String, _
BYVAL Supplierid As Integer, Byval CategoryID AS INTEGER)
DIM CON AS OLEDBCONNECTION
DIM CMD AS Oledbcommand = New OLEDBCommand ()
DIM paramproductname as new oledbparameter ()
Dim paramsupplierid as new oledbparameter ()
DIM paramcategoryid as new oledbparameter ()
Con = New OLEDBConnection (Connectionstring)
cmd.connection = con
With paramproductname
.Parameeeeee = "inproductname"
.Oledbtype = oledbtype.varchar
.Size = 40
.Value = productname
End with
cmd.parameters.add (paramproductname)
With paramsupplierid
.ParametersAme = "insupplierid"
.Oledbtype = oledbtype.integer
.Size = 4
.Value = support
End with
Cmd.Parameters.Add (paramsupplierid)
With paramcategoryid
.ParametersAme = "incategoryid"
.Oledbtype = oledbtype.integer.size = 4
.Value = categoryid
End with
cmd.parameters.add (paramcategoryID)
cmd.commandtext = "Execute ProcproductsAddItem"
Con.open ()
cmd.executenonquery ()
Con. close ()
End Sub
'This function updates a specific jobtitle record with new data.
Sub ProductSupdateItem (Byval Productid AS INTEGER, _
Byval ProductName As String)
DIM CON AS OLEDBCONNECTION
DIM CMD AS Oledbcommand = New OLEDBCommand ()
DIM paramproductname as new oledbparameter ()
DIM paramproductid as new oledbparameter ()
Con = New OLEDBConnection (Connectionstring)
cmd.connection = con
With paramproductididi
.ParameterName = "inproductid"
.Oledbtype = oledbtype.integer
.Size = 4
.Value = productID
End with
cmd.parameters.add (paramproductid)
With paramproductname
.Parameeeeee = "inproductname"
.Oledbtype = oledbtype.varchar
.Size = 40
.Value = productname
End with
cmd.parameters.add (paramproductname)
cmd.commandtext = "Execute ProcproductsupdateItem"
Con.open ()
cmd.executenonquery ()
Con. close ()
End Sub
'This function deletes One Record from the products TABLE.
Sub ProductsDeleteItem (Byval ProductID AS Integer)
DIM CON AS OLEDBCONNECTION
DIM CMD AS Oledbcommand = New OLEDBCommand ()
DIM paramproductid as new oledbparameter ()
Con = New OLEDBConnection (Connectionstring)
cmd.connection = con
With paramproductididi
.ParameterName = "inproductid"
.Oledbtype = oledbtype.integer
.Size = 4
.Value = productID
End with
cmd.parameters.add (paramproductid)
cmd.commandtext = "Execute ProcproductsDeleteItem"
Con.open ()
cmd.executenonquery ()
Con. close ()
End Sub
END CLASS