VB中控件如何连接动态数据库
1个回答
展开全部
'你要连接什么样的控件?下面是连接DataGrid控件的例子:
Option Explicit
Private Function Selectsql(SQL As String) As ADODB.Recordset '返回ADODB.Recordset对象
Dim ConnStr As String
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set Conn = New ADODB.Connection
'On Error GoTo MyErr:
ConnStr = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Password=001234;Initial Catalog=数据库名;Data Source=MERRYCHINA" '这是连接SQL数据库的语句
Conn.Open ConnStr
rs.CursorLocation = adUseClient
rs.Open Trim$(SQL), Conn, adOpenDynamic, adLockOptimistic
Set Selectsql = rs
'Exit Function
'MyErr:
'Set rs = Nothing
'Set Conn = Nothing '释放相关的系统资源
'MsgBox Err.Description, vbInformation, "系统提示" '显示出错信息
End Function
Private Sub Form_Load()
Dim rs As ADODB.Recordset
Set rs = Selectsql(" select * from 表名")
If rs.RecordCount > 0 Then
Set DataGrid1.DataSource = rs
DataGrid1.Refresh
End If
End Sub
Option Explicit
Private Function Selectsql(SQL As String) As ADODB.Recordset '返回ADODB.Recordset对象
Dim ConnStr As String
Dim Conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set Conn = New ADODB.Connection
'On Error GoTo MyErr:
ConnStr = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Password=001234;Initial Catalog=数据库名;Data Source=MERRYCHINA" '这是连接SQL数据库的语句
Conn.Open ConnStr
rs.CursorLocation = adUseClient
rs.Open Trim$(SQL), Conn, adOpenDynamic, adLockOptimistic
Set Selectsql = rs
'Exit Function
'MyErr:
'Set rs = Nothing
'Set Conn = Nothing '释放相关的系统资源
'MsgBox Err.Description, vbInformation, "系统提示" '显示出错信息
End Function
Private Sub Form_Load()
Dim rs As ADODB.Recordset
Set rs = Selectsql(" select * from 表名")
If rs.RecordCount > 0 Then
Set DataGrid1.DataSource = rs
DataGrid1.Refresh
End If
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询