急急急急急!!!!!!vb.net如何连接sql数据库,跪求详细步骤(完全新手)

2024-11-23 10:19:54
推荐回答(1个)
回答1:

Private privateConnection As SqlConnection
Private privateCommand As SqlCommand
Private privateSQLDataAdapter As SqlDataAdapter
Private privateDataSet As DataSet

private function getConnection(byval Server as string,byval Database as string,byval UserName as string,byval Password as string) as string
dim strConnectionString as string
strConnectionString = "Server=" + Server + ";Database=" + Database + ";User ID=" + UserName + ";Password=" + Password + ";"
return strConnectionString
end function

Public Function runSQLDataSet(ByVal SQL As String, Optional ByVal TableName As String = Nothing) As DataSet
Try
privateCommand = New SqlCommand(SQL, privateConnection)
privateDataSet = New DataSet
privateSQLDataAdapter = New SqlDataAdapter(privateCommand)

If TableName = Nothing Then
privateSQLDataAdapter.Fill(privateDataSet)
Else
privateSQLDataAdapter.Fill(privateDataSet, TableName)
End If
privateConnection.Close()
Return privateDataSet
Catch ExceptionObject As Exception
messagebox.show ExceptionObject.message
Finally
privateConnection.Close()
End Try
End Function

'以下为调用
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
privateConnection = New SqlConnection(getConnection("Server","Database","UserName","Password"))
dim dstTmp as dataset
dstTmp=runSQLDataSet("select * from 表1","自定义dataset中表名")
End Sub

以上是简单的代码实现
不知道你有没有安装MSDN帮助文件,其实里面有很详细的说明