有了第一遍用繁琐的经历,这次重构后 抽出个SQLHelp,才知道SQLHelp的清新可爱之处,嘻嘻. 凡事,贵在经历!
'------------------------------------------------------------------------------
' <copyright file="SQLHelp.vb" company="FANG">
' Copyright (c) 2012 FANG. All rights reserved.
' <copyright>
' <author>The Sky Always Sunshine<author>
' <author>我的博客地址http://blog.csdn.net/xhf55555</author>
' <date>2012年2月3日<date>
' <description>
'数据库操作助手类。提炼出查询增删改等所有重复的代码,供所有的DAL层模块调用。 <description>
'------------------------------------------------------------------------------
Public Class SQLHelp
''' <summary>
''' 用配置文件定义的连接数据库的字符串。
''' </summary>
''' <remarks></remarks>
Dim connStr As String = System.Configuration.ConfigurationSettings.AppSettings("ConnStr")
'实例话连接数据库的对象。
Dim conn As SqlConnection = New SqlConnection(connStr)
''' <summary>
''' 传递执行的语句和参数。执行增删改语句返回的Boolean类型。
''' </summary>
''' <param name="SqlStr"></param>
''' <param name="SqlParameter"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExecuteAddDeleteUpdate(ByVal SqlStr As String, ByVal SqlParameter As SqlParameter()) As Boolean
'定义command对象类来执行相关操作。
Dim cmd As SqlCommand = New SqlCommand(SqlStr, conn)
Dim Result As Boolean = False
For i = 0 To SqlParameter.Length - 1
cmd.Parameters.Add(SqlParameter(i))
Next i
'打开数据库。
conn.Open()
Result = cmd.ExecuteNonQuery() > 0
conn.Close()
Return Result
End Function
''' <summary>
''' 执行增删 更新,返回Boolean类型.
''' </summary>
''' <param name="SqlStr"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExecuteAddDeleteUpdate(ByVal SqlStr As String)
Dim cmd As SqlCommand = New SqlCommand(SqlStr, conn)
Dim Result As Boolean = False
'打开数据库。
conn.Open()
Result = cmd.ExecuteNonQuery() > 0
conn.Close()
Return Result
End Function
''' <summary>
''' 执行查询语句返回DataSet
''' </summary>
''' <param name="SqlStr"></param>
''' <param name="SqlParamter"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExecuteQuery(ByVal SqlStr As String, ByVal SqlParamter As SqlParameter()) As DataSet
Dim cmd As SqlCommand = New SqlCommand(SqlStr, conn)
For i = 0 To SqlParamter.Length - 1
cmd.Parameters.Add(SqlParamter(i))
Next
Dim dt As New DataSet
Dim dap As New SqlDataAdapter(cmd)
conn.Open()
dap.Fill(dt)
Return dt
End Function
''' <summary>
''' 执行查询语句返回DataSet。
''' </summary>
''' <param name="SqlStr"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ExecuteQuery(ByVal SqlStr As String) As DataSet
Dim cmd As SqlCommand = New SqlCommand(SqlStr, conn)
Dim dt As New DataSet
Dim dap As New SqlDataAdapter(cmd)
conn.Open()
dap.Fill(dt)
conn.Close()
Return dt
End Function
End Class