重构一段时间会发现,只要跟数据库打交道都会用到那么几行一模一样的代码(貌似每个窗体都必须跟数据库打交道哈),在米老师一遍又一遍的强调面向对象的抽象封装之后,就想着把这些重复的东东抽出来封装成一个类,这样每次用的时候直接调用即可。SQLHelper就解决了这个问题。
在SQLHelper中主要有四类:①带参数的增删改语句或存储过程②不带参数的增删改语句或存储过程③带参数的查询语句或存储过程(返回DataTable结果集)④不带参数的查询语句或存储过程(返回DataTable结果集)
SQLHelper的使用
1、通过配置文件获取连接字符串
<appSettings> <add key="dbString" value="Sqlserver" /> <add key="strConnection" value="server=.;database=JF;UID=sa;PWD=123456" /> <add key="ClientSettingsProvider.ServiceUri" value="" /> </appSettings>2、SQLHelper类
Imports System.Data.SqlClient Imports System.Configuration Public Class SqlHelper '定义变量 '获得数据库连接字符串 Private ReadOnly strConnection As String = ConfigurationSettings.AppSettings("strConnection") '设置连接 Dim conn As SqlConnection = New SqlConnection(strConnection) '定义cmd 命令 Dim cmd As New SqlCommand ''' <summary> ''' 执行增删改三个操作,(有参)返回值为Boolean类型,确认是否执行成功 ''' </summary> '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param> ''' <param name="paras">参数数组,无法确认有多少参数</param> ''' <returns></returns> '''<remarks></remarks> Public Function ExecAddDelUpdate(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As Boolean '将传入的值,分别为cmd的属性赋值 cmd.Parameters.AddRange(paras) '将参数传入 cmd.CommandType = cmdType '设置一个值,解释cmdText cmd.Connection = conn '设置连接,全局变量 cmd.CommandText = cmdText '设置查询的语句 Try conn.Open() '打开连接 Return cmd.ExecuteNonQuery() '执行增删改操作 cmd.Parameters.Clear() '清除参数 Catch ex As Exception MsgBox(ex.Message, , "数据库操作") '如果出错,返回0 Return False Finally Call CloseConn(conn) Call CloseCmd(cmd) End Try End Function ''' <summary> ''' 执行增删改三个操作,(无参)返回值为Boolean类型,确认是否执行成功 ''' </summary> '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param> ''' <returns>Interger,受影响的行数</returns> '''<remarks></remarks> Public Function ExecAddDelUpdateNo(ByVal cmdText As String, ByVal cmdType As CommandType) As Boolean '为要执行的命令cmd赋值 cmd.CommandText = cmdText '先是查询的sql语句 cmd.CommandType = cmdType '设置Sql语句如何解释 cmd.Connection = conn '设置连接 '执行操作 Try conn.Open() Return cmd.ExecuteNonQuery() Catch ex As Exception MsgBox(ex.Message, , "数据库操作") '如果出错,返回0 Return False Finally Call CloseConn(conn) Call CloseCmd(cmd) End Try End Function ''' <summary> ''' 执行查询操作,(有参),返回值为datatable类型,参数不限 ''' </summary> '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param> '''<param name="paras">传入的参数</param> ''' <returns></returns> '''<remarks></remarks> Public Function ExecSelect(ByVal cmdText As String, ByVal cmdType As CommandType, ByVal paras As SqlParameter()) As DataTable Dim sqlAdapter As SqlDataAdapter Dim dt As New DataTable Dim ds As New DataSet '给cmd赋值 cmd.CommandText = cmdText cmd.CommandType = cmdType cmd.Connection = conn cmd.Parameters.AddRange(paras) '参数添加 sqlAdapter = New SqlDataAdapter(cmd) '实例化adapter Try sqlAdapter.Fill(ds) '用adapter将dataset填充 dt = ds.Tables(0) cmd.Parameters.Clear() Catch ex As Exception 'MsgBox(" 查询失败", CType(vbOKOnly + MsgBoxStyle.Exclamation, MsgBoxStyle), "警告") MsgBox(ex.Message, , "数据库操作") '如果出错,返回0 Finally Call CloseCmd(cmd) End Try Return dt End Function ''' <summary> ''' 执行查询操作,(无参),返回值为datatable类型 ''' </summary> '''<param name="cmdText">需要执行语句,一般是Sql语句,也有存储过程</param> '''<param name="cmdType">判断Sql语句的类型,一般都不是存储过程</param> ''' <returns>dataTable,查询到的表格</returns> '''<remarks></remarks> Public Function ExecSelectNo(ByVal cmdText As String, ByVal cmdType As CommandType) As DataTable Dim sqlAdapter As SqlDataAdapter Dim dt As New DataTable Dim ds As New DataSet '给cmd赋值 cmd.CommandText = cmdText cmd.CommandType = cmdType cmd.Connection = conn sqlAdapter = New SqlDataAdapter(cmd) '实例化adapter Try sqlAdapter.Fill(ds) '用adapter将dataset填充 dt = ds.Tables(0) 'datatable为dataSet的第一个表 Catch ex As Exception MsgBox(ex.Message, , "数据库操作") '如果出错,返回0 Finally Call CloseCmd(cmd) End Try Return dt End Function ''' <summary> ''' 关闭连接 ''' </summary> '''<param name="conn ">需要关闭的连接</param> '''<remarks></remarks> Public Sub CloseConn(ByVal conn As SqlConnection) If (conn.State <> ConnectionState.Closed) Then '如果没有关闭 conn.Close() '关闭连接 conn = Nothing '不指向原对象 End If End Sub ''' <summary> ''' 关闭命令 ''' </summary> '''<param name="cmd ">需要关闭的命令 </param> '''<remarks></remarks> Public Sub CloseCmd(ByVal cmd As SqlCommand) If Not IsNothing(cmd) Then '如果cmd命令存在 cmd.Dispose() '销毁 cmd = Nothing End If End Sub End Class3、具体的D层应用
以查询用户为例
使用前:
''' <summary> ''' 查询用户 ''' </summary> ''' <param name="userinfoentity"></param> ''' <returns></returns> ''' <remarks></remarks> Function SelectUser(ByVal userinfoentity As Entity.UserInfoEntity) Dim conn As New SqlConnection '创建连接对象 Dim cmd As New SqlCommand '创建命令对象 conn = New SqlConnection(Dbutil.connstring()) '连接数据库 cmd.Connection = conn '获取SQL语句的内容 Dim reader As SqlDataReader '定义SqlDataReader的变量reader '定义SQL语句 cmd.CommandText = "Select * from UserInfo where UserID='" & userinfoentity.UserID & "'and Password='" & userinfoentity.Password & "'" cmd.CommandType = CommandType.Text conn.Open() '打开数据库链接 reader = cmd.ExecuteReader() '执行查询语句,生成一个DataReader Dim userinfoentity1 As New Entity.UserInfoEntity '读取查询到的数据,返回相应属性 While reader.Read() userinfoentity1.UserID = reader.GetString(0) userinfoentity1.Password = reader.GetString(1) End While Return userinfoentity1 End Function使用后:
Function SelectUser(ByVal userinfoentity As Entity.UserInfoEntity) As List(Of Entity.UserInfoEntity) Dim sql As New SQLHelper.SqlHelper Dim dt As DataTable Dim mylist As List(Of Entity.UserInfoEntity) Dim sqlparams As SqlParameter() Dim strsql As String sqlparams = {New SqlParameter("@UserID", userinfoentity.UserID), New SqlParameter("@Password", userinfoentity.Password)} strsql = "Select * from UserInfo where UserID=@UserID and Password=@Password" dt = sql.ExecSelect(strsql, CommandType.Text, sqlparams) mylist = ConvertHelper.convertToList(Of Entity.UserInfoEntity)(dt) Return mylist End Function小结:
就代码量而言,SQLHelper的作用已经很明显了,简化了重复去屑的那些数据库连接(SQLConnection),SQLCommand和SQLDataReader等,只需要根据实际情况进行传参和SQL语句的改变就可以了。相当方便。