Working with MS Access Stored Procedures in VB.NET Montaque(转贴)

本文介绍了在Microsoft Access中使用存储过程的方法。先阐述了Access存储过程的工作原理,接着详细说明了如何使用ADO.NET和Visual Basic.NET创建存储过程,还展示了创建查询、删除、添加和更新存储过程的SQL语句,最后指出了Access存储过程存在的一些限制。
Working with MS Access Stored Procedures in VB.NET. Part 1
by


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 has 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 cannot be created or run through the Access User Interface. The way to get them into your database is to simply code them. I'll show how that'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. Using the Northwind database that comes with Access, four stored procedures will be created. Focusing on the Products table for all of them, let's start off with the easiest one; select all data of each row in the table. To create the stored procedure, execute the following 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. Consider that you may want to delete a record based 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;"

Notice that a comma separates each parameter when more than one is specified.

Limitations

There are some limitations you may encounter here, especially if you're used to the power of SQL Server.

  • Output parameters cannot be used.
  • Don't use the @ character. The @ character is often used in Transact SQL (SQL Server), where it represents a local variable. Access doesn't 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 presented 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;"
        CreateStoredProc(sSQL)

        ' procProductsDeleteItem - Returns the details (one record) from the 
        ' JobTitle table
        sSQL = "CREATE PROC procProductsDeleteItem(@ProductID LONG) AS " _
            & "DELETE FROM Products WHERE ProductID = @ProductID;"
        CreateStoredProc(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);"
        CreateStoredProc(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;"
        CreateStoredProc(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



Article source code: msaccess_sp2.zip

Introduction

Welcome 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 way. 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 - Code

It'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 accessible from other code modules. After the class is defined all properties are declared:

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 representing 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 ProductID 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.

Entire DBTier.vb source code:

Imports System
Imports System.Data
Imports System.Data.OleDb

' Functions and subroutines for executing Stored Procedures in Access.
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(sSQLcon)
        ds = New DataSet()
        da.Fill(ds"Products")

        Return ds

    End Function

    ' This Function adds one record to the Products table.
    Sub ProductsAddItem(ByVal ProductName As String_
        ByVal SupplierID As IntegerByVal 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
            .ParameterName = "inProductName"
            .OleDbType = OleDbType.VarChar
            .Size = 40
            .Value = ProductName
        End With
        cmd.Parameters.Add(paramProductName)

        With paramSupplierID
            .ParameterName = "inSupplierID"
            .OleDbType = OleDbType.Integer
            .Size = 4
            .Value = SupplierID
        End With
        cmd.Parameters.Add(paramSupplierID)

        With paramCategoryID
            .ParameterName = "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 paramProductID
            .ParameterName = "inProductID"
            .OleDbType = OleDbType.Integer
            .Size = 4
            .Value = ProductID
        End With
        cmd.Parameters.Add(paramProductID)

        With paramProductName
            .ParameterName = "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 paramProductID
            .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
 
内容概要:本文围绕“基于线性决策规则的分布鲁棒机组组合研究”展开,提出了一种应对电力系统中不确定性因素(如风电出力波动)的先进优化建模方法。通过引入线性决策规则(Linear Decision Rules, LDR),将原本难以求解的分布鲁棒优化问题转化为具有较强计算可行性的数学形式,在保证调度方案经济性的同时显著提升了系统在不确定环境下的鲁棒性与可靠性。研究详细阐述了模型构建的关键环节,包括不确定集合的构造、决策变量对不确定参数的仿射依赖关系设计、目标函数与约束条件的精确数学表达,并依托Matlab平台完成了完整的代码实现与仿真验证,充分展示了该方法在计算效率与调度性能之间的良好平衡。; 适合人群:具备电力系统优化、运筹学与凸优化理论基础,熟悉Matlab编程语言,从事高比例可再生能源并网、鲁棒调度、电力系统规划与运行等方向研究的研究生、高校科研人员及电力行业工程技术专家。; 使用场景及目标:① 解决含大规模风电等波动性电源的机组组合问题,提升调度方案对出力不确定性的适应能力与系统安全性;② 深入学习和掌握分布鲁棒优化理论与线性决策规则在复杂电力工程问题中的建模思想、实现技巧与实际应用价值;③ 为现代电力系统的安全、经济、可靠运行提供先进的理论工具与技术支撑。; 阅读建议:建议读者结合Matlab代码实现部分,深入理解线性决策规则的数学原理、近似机制及其在降低问题复杂度方面的有效性,优先复现文中仿真结果,并可进一步探索不同类型的不确定集(如椭球集、多面体集)或更高阶决策规则对优化结果与计算负担的影响,以深化对该方法性能边界的认识。
内容概要:本文提出了一种面向综合能源系统的算力-电力-热力联合优化调度策略,旨在实现多能源耦合系统中的高效协同运行。研究通过构建涵盖算力负荷(如数据中心计算任务)、电力系统与热力系统的综合模型,利用Matlab进行仿真与优化求解,深入整合三者的能量流动关系与动态耦合特性。重点分析了算力负载的时空迁移特性及其对电力与热力供需平衡的影响机制,引入先进的优化算法实现系统经济性、能效性和可再生能源消纳能力的多目标协同优化。该方法有效提升了综合能源系统的资源综合利用效率,降低了运行成本,并增强了系统灵活性与可持续性。; 适合人群:具备电力系统、能源工程、自动化或相关领域背景,熟悉Matlab编程,从事综合能源系统、智能电网、数据中心能耗管理或能源互联网研究的研发人员与高校研究生。; 使用场景及目标:①应用于数据中心与区域能源系统协同调度的实际工程场景;②服务于科研中对多能耦合系统建模、优化算法设计与验证的需求;③实现节能减排、提升系统运行经济性与对可再生能源的高比例消纳目标。; 阅读建议:建议结合提供的Matlab代码深入理解模型构建、变量定义与求解流程,重点关注算力与能源系统间的耦合建模方法,可通过调整负荷参数、引入新的约束条件或更换优化算法进行二次开发与拓展研究。
内容概要:本文研究了基于Q-Learning自适应强化学习的PID控制器在自主水下航行器(AUV)中的应用,旨在提升其在复杂水下环境中运动控制的精度、稳定性和自适应能力。通过建立AUV的六自由度动力学模型,将Q-Learning算法与传统PID控制相结合,实现了对PID参数的在线自整定。文中详细设计了强化学习的状态空间、动作空间与奖励函数,构建了智能优化的控制框架。仿真结果表明,相较于传统固定参数PID控制器,该方法在轨迹跟踪精度、抗外部干扰能力和系统动态响应性能方面均有显著提升,有效解决了非线性、强耦合、时变参数等挑战,验证了智能控制策略在水下机器人系统中的可行性与优越性。; 适合人群:具备自动控制理论、强化学习基础或水下机器人建模相关知识,从事控制工程、自动化、海洋工程、机器人学等领域的科研人员及研究生。; 使用场景及目标:①应用于复杂海洋环境下AUV的高精度运动控制与自主导航;②为智能控制算法在非线性、强耦合动态系统中的工程实现提供技术参考;③推动强化学习与经典控制理论融合的创新研究与实际部署。; 阅读建议:建议读者结合提供的Matlab代码进行仿真实验,重点理解Q-Learning与PID参数调节之间的交互机制,深入分析状态定义、动作选择与奖励函数设计的合理性,从而掌握智能自适应控制系统的构建方法与优化思路。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值