这是我一个程序里的模块,你试试吧
Imports System.Data
Imports System.Data.SqlClient
Module modSQLData
Public ConnStr As String = "Persist Security Info=False;User ID=XXX;Password=XXX;Initial Catalog=XXX;Data Source=XXX;" '连接字符串
Dim Conn As SqlConnection 'conn对象
#Region "填充返回dataset"
Public Function FillDataSet(ByVal SQLStr As String) As DataSet
Try
Conn = New SqlConnection(ConnStr)
Conn.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter(SQLStr, Conn)
Dim ds As DataSet = New DataSet
da.Fill(ds)
Return ds
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Information, "提示")
Finally
Conn.Close()
End Try
End Function
#End Region
#Region "执行SQL语句"
Public Function EXESQLCommand(ByVal SqlStr As String) As Boolean
Try
Conn = New SqlConnection(ConnStr)
Conn.Open()
Dim SqlCmd As SqlCommand
SqlCmd = New SqlCommand(SqlStr, Conn)
SqlCmd.ExecuteNonQuery()
Return True
Catch ex As Exception
MsgBox(ex.Message.ToString, MsgBoxStyle.Information, "提示")
Finally
Conn.Close()
End Try
End Function
#End Region
#Region "执行统计"
Public Function EXESQLScalar(ByVal SqlStr As String) As Single
Try
Conn = New SqlConnection(ConnStr)
Conn.Open()
Dim SqlSc As SqlCommand
Dim SqlCount As Single
SqlSc = New SqlCommand(SqlStr, Conn)
SqlCount = SqlSc.ExecuteScalar()
EXESQLScalar = SqlCount
Catch ex As Exception
'MsgBox(ex.Message.ToString, MsgBoxStyle.Information, "提示")
EXESQLScalar = 0
Finally
Conn.Close()
End Try
End Function
#End Region
如果要从数据库里取出数据显示在Datagridview上,那么如此使用:
dim SQLStr as string="select * from xxx"
DataGridView1.DataSource = FillDataSet(SQLStr).Tables(0)
如果要执行命令,如新增,删除,更新
dim SQLStr as string="inner........delete........update........"
EXESQLCommand(sqlstr)