大家帮忙看看读取数据库哪错了,急~!!
谁来帮我看看下面的代码怎么总是提示错误呢?
目的:读取表mytable里的两个字段code和name,
窗体上有两个Text文本框,在text1中输入code后单击command1后在text2中显示name。
Dim con As New ADODB.Connection
Dim rst As New ADODB.Recordset
Private Sub Command1_Click()
con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Mydb;Data Source=. "
con.Open
sql = "select code,name from mytable where name= ' " & Text1.Text & " ' "
rst.Open sql, con, adOpenStatic, adLockOptimistic
Text2.Text = rst.Fields( "name ").Value
运行时总是弹出如下错误提示:bof或eof中有一个是真,或当前记录已被删除。
但我明明看着数据库里有这条记录就是查不出来,郁闷,各位帮帮忙。怎么回事呢?
[解决办法]
sql = "select [code],[name] from mytable where [name]= ' " & Text1.Text & " ' "
if rst.state=adstateopen then rst.close
rst.Open sql, con, adOpenStatic, adLockOptimistic
if rst.recordcount=0 then
text2.text= " "
else
Text2.Text = rst![name] & " "
end if
rst.close
[解决办法]
Text2.Text = rst![name] & " "
其中的!代表什么意思,为什么后面还要并上一个空字符呢?
是考虑 rst![name] 是NULL的情况