VB.net版本的数据库访问类DataBaseAccess_vb.net access begintransaction-程序员宅基地

技术标签: exception  VB.NET  integer  vb.net  数据库  parameters  command  

 在开发一个VB.net的项目时,曾经整理出了一个DataBaseAccess的访问类,现在将该类分享下:
Imports System
Imports System.IO
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient

 


Namespace SqlDataProvider

 

    Public Class DataBaseAccess

#Region "Local Property Declaration"

        Dim _connectionString As String

#End Region

#Region " Constructor "

        ''' <summary>
        ''' Initializes a new instance of the ADO.SqlDatabase class.
        ''' </summary>
        ''' <param name="connectionString">The connection used to open the SQL Server database.</param>
        Public Sub New(ByVal connectionString As String)
            _connectionString = connectionString
        End Sub

#End Region

#Region " Public Properties "

        ''' <summary>
        ''' Gets or sets the string used to open a SQL Server database.
        ''' </summary>
        ''' <returns>The connection string that includes the source database name, and other parameters needed to establish the initial connection.</returns>
        Public Property ConnectionString() As String
            Get
                Return _connectionString
            End Get
            Set(ByVal value As String)
                _connectionString = value
            End Set
        End Property

#End Region

#Region " Private Methods "

        Private Sub AssignParameters(ByVal cmd As SqlCommand, ByVal cmdParameters() As SqlParameter)
            If (cmdParameters Is Nothing) Then Exit Sub
            For Each p As SqlParameter In cmdParameters
                cmd.Parameters.Add(p)
            Next
        End Sub

        Private Sub AssignParameters(ByVal cmd As SqlCommand, ByVal parameterValues() As Object)
            If Not (cmd.Parameters.Count - 1 = parameterValues.Length) Then Throw New ApplicationException("Stored procedure's parameters and parameter values does not match.")
            Dim i As Integer
            For Each param As SqlParameter In cmd.Parameters
                If Not (param.Direction = ParameterDirection.Output) AndAlso Not (param.Direction = ParameterDirection.ReturnValue) Then
                    param.Value = parameterValues(i)
                    i += 1
                End If
            Next
        End Sub

#End Region

#Region " ExecuteNonQuery "

        ''' <summary>
        ''' Executes a Transact-SQL statement against the connection and returns the number of rows affected.
        ''' </summary>
        ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param>
        ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
        ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param>
        ''' <returns>The number of rows affected.</returns>
        Public Function ExecuteNonQuery(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Integer
            Dim connection As SqlConnection = Nothing
            Dim transaction As SqlTransaction = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As Integer = -1
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(cmd, connection)
                command.CommandType = cmdType
                Me.AssignParameters(command, parameters)
                connection.Open()
                transaction = connection.BeginTransaction()
                command.Transaction = transaction
                res = command.ExecuteNonQuery()
                transaction.Commit()
            Catch ex As Exception
                If Not (transaction Is Nothing) Then
                    transaction.Rollback()
                End If
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
                If Not (command Is Nothing) Then command.Dispose()
                If Not (transaction Is Nothing) Then transaction.Dispose()
            End Try
            Return res
        End Function

        ''' <summary>
        ''' Executes a Transact-SQL statement against the connection and returns the number of rows affected.
        ''' </summary>
        ''' <param name="spname">The stored procedure to execute at the data source.</param>
        ''' <param name="returnValue">The returned value from stored procedure.</param>
        ''' <param name="parameterValues">The parameter values of the stored procedure.</param>
        ''' <returns>The number of rows affected.</returns>
        Public Function ExecuteNonQuery(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As Integer
            Dim connection As SqlConnection = Nothing
            Dim transaction As SqlTransaction = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As Integer = -1
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(spname, connection)
                command.CommandType = CommandType.StoredProcedure
                connection.Open()
                SqlCommandBuilder.DeriveParameters(command)
                Me.AssignParameters(command, parameterValues)
                transaction = connection.BeginTransaction()
                command.Transaction = transaction
                res = command.ExecuteNonQuery()
                returnValue = command.Parameters(0).Value
                transaction.Commit()
            Catch ex As Exception
                If Not (transaction Is Nothing) Then
                    transaction.Rollback()
                End If
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
                If Not (command Is Nothing) Then command.Dispose()
                If Not (transaction Is Nothing) Then transaction.Dispose()
            End Try
            Return res
        End Function

#End Region

#Region " ExecuteScalar "

        ''' <summary>
        ''' Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
        ''' </summary>
        ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param>
        ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
        ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param>
        ''' <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
        Public Function ExecuteScalar(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As Object
            Dim connection As SqlConnection = Nothing
            Dim transaction As SqlTransaction = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As Object = Nothing
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(cmd, connection)
                command.CommandType = cmdType
                Me.AssignParameters(command, parameters)
                connection.Open()
                transaction = connection.BeginTransaction()
                command.Transaction = transaction
                res = command.ExecuteScalar()
                transaction.Commit()
            Catch ex As Exception
                If Not (transaction Is Nothing) Then
                    transaction.Rollback()
                End If
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
                If Not (command Is Nothing) Then command.Dispose()
                If Not (transaction Is Nothing) Then transaction.Dispose()
            End Try
            Return res
        End Function

        ''' <summary>
        ''' Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
        ''' </summary>
        ''' <param name="spname">The stored procedure to execute at the data source.</param>
        ''' <param name="returnValue">The returned value from stored procedure.</param>
        ''' <param name="parameterValues">The parameter values of the stored procedure.</param>
        ''' <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
        Public Function ExecuteScalar(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As Object
            Dim connection As SqlConnection = Nothing
            Dim transaction As SqlTransaction = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As Object = Nothing
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(spname, connection)
                command.CommandType = CommandType.StoredProcedure
                connection.Open()
                SqlCommandBuilder.DeriveParameters(command)
                Me.AssignParameters(command, parameterValues)
                transaction = connection.BeginTransaction()
                command.Transaction = transaction
                res = command.ExecuteScalar()
                returnValue = command.Parameters(0).Value
                transaction.Commit()
            Catch ex As Exception
                If Not (transaction Is Nothing) Then
                    transaction.Rollback()
                End If
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
                If Not (command Is Nothing) Then command.Dispose()
                If Not (transaction Is Nothing) Then transaction.Dispose()
            End Try
            Return res
        End Function

#End Region

#Region " ExecuteReader "

        ''' <summary>
        ''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection, and builds a System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values.
        ''' </summary>
        ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param>
        ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
        ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param>
        ''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns>
        Public Function ExecuteReader(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As IDataReader
            Dim connection As SqlConnection = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As SqlDataReader = Nothing
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(cmd, connection)
                command.CommandType = cmdType
                Me.AssignParameters(command, parameters)
                connection.Open()
                res = command.ExecuteReader(CommandBehavior.CloseConnection)
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            End Try
            Return CType(res, IDataReader)
        End Function

        ''' <summary>
        ''' Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection, and builds a System.Data.SqlClient.SqlDataReader using one of the System.Data.CommandBehavior values.
        ''' </summary>
        ''' <param name="spname">The stored procedure to execute at the data source.</param>
        ''' <param name="returnValue">The returned value from stored procedure.</param>
        ''' <param name="parameterValues">The parameter values of the stored procedure.</param>
        ''' <returns>A System.Data.SqlClient.SqlDataReader object.</returns>
        Public Function ExecuteReader(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As IDataReader
            Dim connection As SqlConnection = Nothing
            Dim command As SqlCommand = Nothing
            Dim res As SqlDataReader = Nothing
            Try
                connection = New SqlConnection(ConnectionString)
                command = New SqlCommand(spname, connection)
                command.CommandType = CommandType.StoredProcedure
                connection.Open()
                SqlCommandBuilder.DeriveParameters(command)
                Me.AssignParameters(command, parameterValues)
                res = command.ExecuteReader(CommandBehavior.CloseConnection)
                returnValue = command.Parameters(0).Value
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            End Try
            Return CType(res, IDataReader)
        End Function

#End Region

#Region " FillDataset "

        ''' <summary>
        ''' Adds or refreshes rows in the System.Data.DataSet to match those in the data source using the System.Data.DataSet name, and creates a System.Data.DataTable named "Table."
        ''' </summary>
        ''' <param name="cmd">The Transact-SQL statement or stored procedure to execute at the data source.</param>
        ''' <param name="cmdType">A value indicating how the System.Data.SqlClient.SqlCommand.CommandText property is to be interpreted.</param>
        ''' <param name="parameters">The parameters of the Transact-SQL statement or stored procedure.</param>
        ''' <returns>A System.Data.Dataset object.</returns>
        Public Function FillDataset(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As DataSet
            Dim connection As SqlConnection = Nothing
            Dim command As SqlCommand = Nothing
            Dim sqlda As SqlDataAdapter = Nothing
            Dim res As New DataSet
            Try
                connection = New SqlConnection(_connectionString)
                command = New SqlCommand(cmd, connection)
                command.CommandType = cmdType
                AssignParameters(command, parameters)
                sqlda = New SqlDataAdapter(command)
                sqlda.Fill(res)
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) Then connection.Dispose()
                If Not (command Is Nothing) Then command.Dispose()
                If Not (sqlda Is Nothing) Then sqlda.Dispose()
            End Try
            Return res
        End Function

#End Region

#Region " ExecuteDataset "

        ''' <summary>
        ''' Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the System.Data.DataSet with the specified System.Data.DataTable name.
        ''' </summary>
        ''' <param name="insertCmd">A command used to insert new records into the data source.</param>
        ''' <param name="updateCmd">A command used to update records in the data source.</param>
        ''' <param name="deleteCmd">A command for deleting records from the data set.</param>
        ''' <param name="ds">The System.Data.DataSet to use to update the data source. </param>
        ''' <param name="srcTable">The name of the source table to use for table mapping.</param>
        ''' <returns>The number of rows successfully updated from the System.Data.DataSet.</returns>
        Public Function ExecuteDataset(ByVal insertCmd As SqlCommand, ByVal updateCmd As SqlCommand, ByVal deleteCmd As SqlCommand, ByVal ds As DataSet, ByVal srcTable As String) As Integer
            Dim connection As SqlConnection = Nothing
            Dim sqlda As SqlDataAdapter = Nothing
            Dim res As Integer = 0
            Try
                connection = New SqlConnection(_connectionString)
                sqlda = New SqlDataAdapter
                If Not (insertCmd Is Nothing) Then insertCmd.Connection = connection : sqlda.InsertCommand = insertCmd
                If Not (updateCmd Is Nothing) Then updateCmd.Connection = connection : sqlda.UpdateCommand = updateCmd
                If Not (deleteCmd Is Nothing) Then deleteCmd.Connection = connection : sqlda.DeleteCommand = deleteCmd
                res = sqlda.Update(ds, srcTable)
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If Not (connection Is Nothing) Then connection.Dispose()
                If Not (insertCmd Is Nothing) Then insertCmd.Dispose()
                If Not (updateCmd Is Nothing) Then updateCmd.Dispose()
                If Not (deleteCmd Is Nothing) Then deleteCmd.Dispose()
                If Not (sqlda Is Nothing) Then sqlda.Dispose()
            End Try
            Return res
        End Function

#End Region

#Region " ExecuteScript "

        ''' <summary>
        ''' Executes a SQL query file against the connection.
        ''' </summary>
        ''' <param name="filename">SQL query file name.</param>
        ''' <param name="parameters">The parameters of the SQL query file.</param>
        Public Sub ExecuteScript(ByVal filename As String, Optional ByVal parameters() As SqlParameter = Nothing)
            Dim fStream As FileStream = Nothing
            Dim sReader As StreamReader = Nothing
            Dim connection As SqlConnection = Nothing
            Dim command As SqlCommand = Nothing
            Try
                fStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
                sReader = New StreamReader(fStream)
                connection = New SqlConnection(ConnectionString)
                command = connection.CreateCommand()
                connection.Open()
                While (Not sReader.EndOfStream)
                    Dim sb As New StringBuilder
                    While (Not sReader.EndOfStream)
                        Dim s As String = sReader.ReadLine
                        If (Not String.IsNullOrEmpty(s)) AndAlso (s.ToUpper.Trim = "GO") Then
                            Exit While
                        End If
                        sb.AppendLine(s)
                    End While
                    command.CommandText = sb.ToString
                    command.CommandType = CommandType.Text
                    AssignParameters(command, parameters)
                    command.ExecuteNonQuery()
                End While
            Catch ex As Exception
                Throw New Exception(ex.Message, ex.InnerException)
            Finally
                If (Not IsNothing(connection)) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
                If (Not IsNothing(command)) Then command.Dispose()
                If (Not IsNothing(sReader)) Then sReader.Close()
                If (Not IsNothing(fStream)) Then fStream.Close()
            End Try
        End Sub

#End Region


    End Class

End Namespace

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weizhiai12/article/details/6826421

智能推荐

webhooks是什么啊?有什么好处?_wedhook-程序员宅基地

文章浏览阅读387次。你需要向视频处理服务器上传一个视频、你需要获得视频处理后的结果,然而视频处理服务器上视频很多,在排队进行处理,你不能立刻获取到视频的处理结果,此时你可以设计一个hook url,当视频处理完成后,视频处理服务器自动向你的hook url发送请求,告诉你视频已经处理完毕.在传统的web server设计中,我们项目A想要获取项目B的数据,通常项目B需要提供一个API,然后项目A去请求项目B的API,从而获得数据,这样的过程我们称之为"拉"数据。==通过webhook机制,对客户端-服务端的模式进行了逆转。_wedhook

解决:Error:java xxxx 程序包不存在_java语言unil程序包不存在什么意思-程序员宅基地

文章浏览阅读3.2w次,点赞8次,收藏9次。今天早上,一跑项目报错了。。java程序包不存在。我是小白啊,之前没有遇到过这种问题就赶紧查了查。终于解决了。其实我遇到的也不是什么大问题,只是该文件下少了上述的jar包(见下图)。再查看 pom 文件没有报错,和 Maven Projects 中的 Dependencies 中都没有缺少这些内容。直接重新导入全部的Maven Projects 就好了。参考文章:..._java语言unil程序包不存在什么意思

java接收ajax传参_Ajax传值以及接受传值,@ResPonseBody 和 @RequestBody-程序员宅基地

文章浏览阅读873次。Ajax对于Java编程人员开说可是很重要的,可以说是必会的。Title// 第二步:使用Jquery的 ajax (被封装过的)来请求数据地址$.ajax({type:'post',url:'api/data.json',data:{},success:function (res) {console.log(res)}})// url: 填写的内容的是 后台的数据接口// type: 本次发送..._java控制层获取ajax传参

【Python】 将一个函数作为参数传递到另一个函数中_python怎么作为参数引入一个方程-程序员宅基地

文章浏览阅读2.6k次,点赞3次,收藏2次。背景:学数据结构的时候需要一个能够测量各种算法消耗时长的函数,重复写,话不多说直接上代码。import time as tdef mutinomial(n,a,x): p = 0 for i in range(0,n+1): p += a[i]*pow(x,i) return print(p)def qinjiushao(n,a,x): p = a[n] for i in range(n,0,-1): p *= x _python怎么作为参数引入一个方程

你训练的神经网络不对头的37个原因-程序员宅基地

文章浏览阅读403次。点击上方“AI公园”,关注公众号,选择加“星标“或“置顶”作者:Slav Ivanov编译:ronghuaiyang导读大家都遇到过这种情况,训练的时候没什么问题,测试的..._神经网络错误直方图的instance

学计算机免修考试,长沙学院非计算机专业学生计算机基础课程免修实施办法-程序员宅基地

文章浏览阅读879次。长大教〔2018〕145号计算机基础课程是非计算机专业人才培养中的基础性课程,是当代大学生必须掌握的基础知识和基本能力。为贯彻因材施教的原则,突出个性化教学的要求,提高教学效率,根据《长沙学院课程考核管理办法》(长大发〔2017〕42号)的精神,经学校研究,决定对非计算机专业学生计算机基础课程作以下免修规定。一、免修的课程非计算机专业的计算机基础课程包括第一学期开设的《大学计算机基础》课程,第二学..._大学计算机免修的条件

随便推点

Comsol事件控制线圈加热冷却(涡流热成像)_comsol涡流检测里线圈-程序员宅基地

文章浏览阅读1.1k次,点赞19次,收藏12次。在涡流加热过程中,通常需要关注的不仅是加热过程,还有加热物体的冷却过程。这非常重要。Xiao XT【】中用试验方法说明了对于缺陷的深度的定量分析,加热与冷却过程的频域图(幅度与相位)十分重要。_comsol涡流检测里线圈

Java——《面试题——MySQL篇》_java mysql面试题-程序员宅基地

文章浏览阅读3.3k次,点赞4次,收藏28次。视图是一种虚拟的表,具有和物理表相同的功能。可以对视图进行增,改,查,操作,试图通常是 有一个表或者多个表的行或列的子集。对视图的修改不影响基本表。它使得我们获取数据更容易, 相比多表查询。内联接(Inner Join):匹配2张表中相关联的记录。左外联接(Left Outer Join):除了匹配2张表中相关联的记录外,还会匹配左表中剩余的记 录,右表中未匹配到的字段用NULL表示。_java mysql面试题

web3j 命令行_web3j 命令行工具-程序员宅基地

文章浏览阅读7.8k次。1. 下载最新的版本已经没有直接的命令行工具了,工具版本v4.5.5 下载2. 可以配置到环境变量3. 命令version: 版本号wallet: create: 生成一个新的以太坊钱包 update:更新现有钱包的密码 send: 将以太币发送到另一个地址solidity: 智能合约new:import:..._web3j 命令行工具

iptables移植到ARM Linux教程_arm-linux iptable源码下载-程序员宅基地

文章浏览阅读5.1k次,点赞5次,收藏10次。http://www.veryarm.com/568.htmliptables或netfilter(网络过滤器)是一个工作于用户空间的防火墙应用软件,允许系统管理员可以调整设置X表(Xtables)提供相关的系统表格(目前主要位于iptables/netfilter)以及相关的“链”与“规则”,以管理网络数据包的流动与转送的动作。Iptables是用户态提供的更改过滤规_arm-linux iptable源码下载

使用Audacity分析浊音、清音、爆破音的时域及频域特性。_audacity 获取当前频率-程序员宅基地

文章浏览阅读398次。文章目录一、实验任务二、实验内容1. 浊音2. 清音3. 爆破音三、实验分析1. 浊音2. 清音3. 爆破音一、实验任务使用Audacity分析浊音、清音、爆破音的时域及频域特性。二、实验内容1. 浊音语音学中,将发音时声带振动的音称为浊音。以浊音U为例,使用Audacity得到时域及频域波形。浊音U时域波形图(如下)浊音U频域波形图(如下)2. 清音语音学中,将发音时声带不振动的音称为清音,与浊音相对。以浊音t为例,使用Audacity得到时域及频域波形。清音t时域波形图(如下)_audacity 获取当前频率

RxJS --响应式编程库_rxjs库-程序员宅基地

文章浏览阅读216次。RxJS 全称 Reactive Extensions for JavaScriptRxJS 结合了函数式编程、观察者模式(例如 DOM EventListener)、迭代器模式(例如 ES6 Iterater)RxJS 官方是这样说的: Think of RxJS as Lodash for events. 把 RxJS 想像成针对 events 的 lodashRxJS 本质是个工具库,处理的是事件,这里的 events,可以称之为流那么流是指什么呢?_rxjs库

推荐文章

热门文章

相关标签