根据表单文本框值获取记录

时间:2014-05-29 08:04:39

标签: sql-server-2008 ms-access-2007

我正在尝试根据表单上文本框中包含的值来获取记录。即我在文本框中输入信息,并将与该值相关联的其他值返回到表单上的其他文本框。

我认为这很容易,但似乎无法让它发挥作用。

目前我正在尝试

Dim rst As DAO.Recordset
Dim SQL As String
Dim SQL2 As String

SQL = "SELECT tblmytbl.[IDCODE]" 
"FROM tblmytbl " & _
"WHERE (((tblmytbl.[IDCODE]) = forms!myform!mybox.value " 

Set db = CurrentDb
Set rst = db.OpenRecordset(SQL)
If Not ((rst.BOF = True) And (rst.EOF = True)) Then
Forms!myform!Text102 = rst.Fields("[Name]")
Forms!myform!Text103 = rst.Fields("[Surname]")enter code here

注意:搜索信息是字母数字,我试过没有.value

任何帮助将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:1)

您发送到服务器的SQL无法访问该表单。但是,您可以将值连接到您发送的字符串,如:

" WHERE (((mytable.myfield) = '" & FixQuotes(Forms!myform!mybox.value) & "') " & _

注意,您可能需要保护自己免受SQL注入,简单(但不完整)的防御将是这样的:

Public Function FixQuotes(input as string) As String
    FixQuotes = Replace(input,"'","''")
End Function

编辑:

根据您更新的代码,您需要进行大量更改。除了上面的陈述,.OpenRecordset仅适用于完整表,您不能将其与SELECT语句一起使用。相反,您必须实例化QueryDef。最重要的是,您尝试引用未包含在查询中的字段。此外,您可以将表达式Forms!myform!简化为Me(如果您希望在其他位置重复使用代码,这可能会有所帮助)所以您的代码应如下所示:

Dim db as Database 'always dim everything, you should use Option Explicit'
Dim rst as Recordset 'DAO is the default anyway'
Dim qdf as QueryDef 'this object is required for queries'

Set db = CurrentDb

'prepare single-use query, to return the values you're going to use
'as mentioned before, the query doesn't have access to the form
'we can use Me since it references the form'
' use TOP 1 since you only expect 1 record'

Set qdf = db.CreateQueryDef("","SELECT TOP 1 Name,Surname FROM tblmytbl " & _
     "WHERE IDCODE = '" & FixQuotes(Me.mybox.value) & "';")

Set rst = qdf.OpenRecordset(DbOpenForwardOnly) 
'forwardonly since you only care about the first record'

If Not rst.EOF Then 'ForwardOnly has to start at the first record'
    Me.Text102.Value = rst!Name
    Me.Text103.Value = rst!Surname
    'I highly suggest giving these boxes better names'
Else
    'no record found'
End if

rst.Close
qdf.Close
db.Close 'close these objects, it can sometimes cause memory leaks otherwise'