- 浏览: 149432 次
- 性别:
- 来自: 深圳
文章分类
最新评论
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
相关推荐
总结一下,创建一个ASP.NET和C#的数据库访问公共类涉及以下关键点: 1. 设计一个抽象基类,定义通用的数据库操作方法。 2. 实现针对特定数据库的子类,覆盖基类的方法,实现数据库特有的功能。 3. 使用工厂模式或者...
《晶晶Vb.net留言板源码》是一款基于Visual Basic .NET开发的简单留言板程序,它融合了Access数据库和XML文件,提供了基础的留言、回复以及后台管理功能。在这个项目中,用户可以方便地进行信息交流,同时管理员可以...
在ASP.NET中,最常用的数据库访问类之一是`SqlClient`,它是.NET Framework的一部分,专门用于与SQL Server数据库进行交互。`SqlConnection`类是连接到SQL Server的桥梁,它提供了打开、关闭和管理数据库连接的方法...
8. **异步操作**:现代应用常常要求高并发性能,因此封装类可能还需要提供异步版本的方法,如`ExecuteNonQueryAsync`、`ExecuteReaderAsync`等,以便在等待数据库响应的同时,程序可以继续执行其他任务。 `说明.txt...
为了高效地与不同类型的数据库进行交互,开发者通常会创建一个通用的数据库访问类(Database Access Layer,DAL),以便在不同场景下复用代码,提高代码的可维护性和可扩展性。本篇文章将深入探讨如何使用Java实现一...
ADO.NET是由微软开发的一套数据访问技术,它为开发者提供了与数据库进行连接、查询、更新和删除数据的能力。在这个“ado数据库操作,适合新手”的主题中,我们将深入探讨如何使用C#和ADO.NET进行数据库操作。 首先...
在 ASP.NET 中,通常会使用 `MySqlConnection` 类来创建数据库连接,然后通过 `MySqlCommand` 来执行 SQL 查询或命令。以下是一个简单的示例,展示如何在 ASP.NET 中连接到 MySQL 数据库: ```csharp using MySql....
在实现数据库访问接口时,我们可以定义一个通用的注解,比如`@DatabaseEntity`,用于标记那些代表数据库表的类。这个注解可以包含如表名、主键等信息。然后,我们可以通过反射获取这些注解信息,动态地创建SQL语句并...
TimeBilling的数据库操作可能封装在如`DatabaseAccess`这样的类中,该类包含了连接数据库、执行SQL语句的方法。 **COM+ Express** COM+(Component Object Model Plus)是微软的一种组件服务技术,它提供了对分布式...
ADO(ActiveX Data Objects)是Microsoft开发的一种数据访问接口,用于在Windows环境下高效地...通过这个压缩包中的"ADO操作数据库的类",你可以进一步学习如何在实际项目中应用这些概念,实现高效的数据访问和操作。
在实现数据库访问类时,通常会创建一个基类或接口,定义通用的方法,如连接数据库、执行SQL语句、调用存储过程等。然后,为每种数据库创建一个具体的子类,继承自基类或实现接口,这样可以在不修改原有代码的情况下...
3. **数据库交互(DatabaseAccess.cs)**:如果游戏记录用户的猜测历史,那么可能需要数据库支持,这部分代码处理数据库连接和查询操作。 4. **样式表(Styles.css)**:为了提供良好的用户体验,页面的布局和样式...
在开发Java Web应用时,数据库访问层通常会通过DAO(Data Access Object)模式或者ORM(Object-Relational Mapping)框架如Hibernate或MyBatis来实现,这些框架可以简化数据库操作并提供更高级的功能。对于大型项目...
3. **Class Files (.cs)**:包含C#源代码的类文件,如"DatabaseAccess.cs"(数据库访问层)、"BusinessLogic.cs"(业务逻辑层)等。 4. **Config Files (配置文件)**:"web.config"或"app.config",用于设置应用程序...
`DatabaseAccess`很可能是一个包含了数据库连接、查询和更新等操作的类,而`Demo`可能是用来演示如何使用`DatabaseAccess`的测试类。 在`DatabaseAccess.java`中,我们通常会看到如下几个关键部分: 1. 数据库连接...
4. 数据访问类(如DatabaseAccess.cs):实现了与数据库的交互,如执行SQL查询以查找用户信息。 学习这个源码,你可以了解如何在ASP.NET中创建HTTP请求,处理表单提交,以及如何在三层架构中分配职责。同时,这也是...
创建一个新的C#类,如`DatabaseAccess.cs`,在这个类中封装数据库操作方法。例如,可以创建一个`OpenConnection()`方法来打开连接,`CloseConnection()`方法关闭连接,以及`ExecuteNonQuery()`和`ExecuteReader()`...
4. **数据访问类(`DatabaseAccess`)**:这是一个封装了数据库操作的类,包含了构造函数、成员变量和方法。构造函数负责初始化数据库连接、命令对象和数据适配器,确保后续的数据查询和操作得以进行。 5. **查询...
- `DataObject`文件夹可能还包含了数据库操作相关的类,如`DatabaseAccess.vb`,这个类可能包含连接数据库、执行SQL语句的方法。 5. **通信机制** - UI层调用BLL层的方法,传递必要的参数,BLL层再调用DAL层的...