首页 > 编程 > .NET > 正文

asp.net下使用DbProviderFactories的数据库操作类

2024-07-10 12:42:14
字体:
来源:转载
供稿:网友
封装数据库操作,并且提供事务处理。
代码如下:
使用DbProviderFactories的数据库操作类
Imports System.Data
Imports System.Configuration
Imports System.Data.Common

'*******************************************************************
'* Page/Class Name:XPDBHelper.vb
'* Title:使用DbProviderFactories的数据库操作类
'* Description:简单三层结构数据库操作类
'* Copyright:
'* Company:
'* @author:Owen,Yuan
'* Create Date:2010/3/9 14:04:56
'* Last Modifier:
'* Last Modify Date:
'*******************************************************************
Public Class XPDBHelper

'取得连接字符串中的数据库驱动提供者
Private Shared dbProviderName As String = ConfigurationManager.ConnectionStrings("ConnectionString").ProviderName

'取得数据库连接字符串
Private Shared dbConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

'数据库连接。
Private connection As DbConnection

Public Sub New()
Me.connection = CreateConnection(XPDBHelper.dbConnectionString)
End Sub

Public Sub New(ByVal connectionString As String)
Me.connection = CreateConnection(connectionString)
End Sub

'创建数据库连接
Public Shared Function CreateConnection() As DbConnection
Dim dbfactory As DbProviderFactory = DbProviderFactories.GetFactory(dbProviderName)
Dim dbconn As DbConnection = dbfactory.CreateConnection()
dbconn.ConnectionString = XPDBHelper.dbConnectionString
Return dbconn
End Function

'创建数据库连接
Public Shared Function CreateConnection(ByVal connectionString As String) As DbConnection
Dim dbfactory As DbProviderFactory = DbProviderFactories.GetFactory(dbProviderName)
Dim dbconn As DbConnection = dbfactory.CreateConnection()
dbconn.ConnectionString = connectionString
Return dbconn
End Function

'根据存储过程创建DbCommand
Public Function GetStoredProcCommond(ByVal storedProcedure As String) As DbCommand
Dim dbCommand As DbCommand = connection.CreateCommand()
dbCommand.CommandText = storedProcedure
dbCommand.CommandType = CommandType.StoredProcedure
Return dbCommand
End Function

'根据SQL语句创建DbCommand
Public Function GetSqlStringCommond(ByVal sqlQuery As String) As DbCommand
Dim dbCommand As DbCommand = connection.CreateCommand()
dbCommand.CommandText = sqlQuery
dbCommand.CommandType = CommandType.Text
Return dbCommand
End Function

#Region "增加参数"
Public Sub AddParameterCollection(ByVal cmd As DbCommand, ByVal dbParameterCollection As DbParameterCollection)
For Each dbParameter As DbParameter In dbParameterCollection
cmd.Parameters.Add(dbParameter)
Next
End Sub

Public Sub AddOutParameter(ByVal cmd As DbCommand, ByVal parameterName As String, ByVal dbType As DbType, ByVal size As Integer)
Dim dbParameter As DbParameter = cmd.CreateParameter()
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表