我是一名vb初学者,曾经为这个问题很苦恼,现在终于写了出来,和我一样的初学者一起进步吧!
我使用ado连接数据库,通过绑定datagrid控件来显示数据库中符合条件的内容。
option explicit
private sub command1_click()
dim cn as new adodb.connection '数据库连接变量
dim cmd as new adodb.command '命令集
dim rs as new adodb.recordset '记录集
dim strconnect as string '连接字符串
set cn = new adodb.connection
strconnect = "provider=sqloledb.1;persist security info=false;user id=sa;initial catalog=database;data source=servername" '指定连接字符串
cn.connectionstring = strconnect
cn.open '连接数据库
with cmd
.activeconnection = cn
.commandtype = adcmdstoredproc '有四种可选择的类型,在编程过程中使用sql server的存储过程是很好的方法
.commandtext = "sp_get_name" '存储过程名称
.parameters.refresh
.parameters("@dt").value = date() '存储过程中参数的值(存储过程中只有一个参数)
end with
with rs
.cursorlocation = aduseclient
.cursortype = adopenstatic
.locktype = adlockreadonly
.open cmd
end with
set datagrid1.datasource = rs '绑定数据库显示控件
end sub
要在datagrid控件中显示数据cursorlocation = aduseclient和set datagrid1.datasource = rs两个语句不可缺少。