不可能每个窗体的连接路径都要改吧!
在Module1.vb里的:
Imports System.Data.SqlClient
Module Module1
Public ConnString As String = "Data Source=.;Initial Catalog=test;User ID=sa"
Function CreateDataSetaa(ByVal strSQL As String, ByVal TableName As String) As DataSet
Dim objCmd As New SqlDataAdapter(strSQL, ConnString)
Dim DS As New DataSet
objCmd.Fill(DS, TableName)
CreateDataSetaa = DS
End Function
End Module
在Form1.vb里的:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strSql As String = "select * from aaa"
DataGrid1.DataSource = CreateDataSetaa(strSql, "aaa")
Me.DataGrid1.DataMember = "aaa"
End Sub
End Class
但我很想知道 single 你的那种写法!
一个标准的建类方法.比如要建立一个名为database的类,代码编写如下:
Imports System.Data
Imports System.Data.SqlClient
Imports System.ComponentModel
Public Class DataBase
'实现接口IDisposable
Implements IDisposable
'数据库连接对象
Private SqlConn As SqlConnection
Public Shared sConn As String = "Persist Security Info=False;Integrated Security=SSPI;database=libbook;server=.;Connect Timeout=30"
Public Sub Dispose() Implements System.IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(True)
End Sub
Protected Sub Dispose(ByVal disposing As Boolean)
If disposing <> True Then
Return
End If
If SqlConn Is Nothing = False Then
SqlConn.Dispose()
SqlConn = Nothing
End If
End Sub
Public Sub Open()
If SqlConn Is Nothing = True Then
'建立数据库连接对象
SqlConn = New SqlConnection(Me.sConn)
'打开数据库连接
SqlConn.Open()
End If
End Sub
Public Sub Close()
'如果数据库连接对象不为空则关闭数据库连接
If SqlConn Is Nothing = False Then
SqlConn.Close()
End If
End Sub
Public Function RunSelectSQL(ByVal sSQLString As System.String) As DataView
Me.Open()
Dim SqlDS As DataSet = New DataSet
Dim SqlDA As SqlDataAdapter = New SqlDataAdapter(sSQLString, Me.SqlConn)
SqlDA.Fill(SqlDS)
Return SqlDS.Tables(0).DefaultView
End Function
Public Function RunDelOrInsSQL(ByVal sSQLString As System.String)
Me.Open()
Dim SqlComm As SqlCommand = New SqlCommand(sSQLString, Me.SqlConn)
SqlComm.ExecuteNonQuery()
End Function
End Class