"SELECT tblStudent.StudentName, tblStudent.Username FROM tblStudent " & _
"INNER JOIN tblClasses/Students ON tblStudent.StudentID = tblClasses/Students.StudentID " & _
"INNER JOIN tblClasses ON tblClasses/Students.ClassID = tblClasses.ClassID " & _
"WHERE tblClasses.ClassName = '" & lstClasses.SelectedItem & "';"
此处,lstClasses.SelectedItem引用tblClasses中的类的名称。我已经测试过,看看这是否是问题所在,但是“ SelectedItem”正是我所希望的,所以这不可能。
答案 0 :(得分:2)
构建这样的字符串:
Dim sql As String = _
"SELECT tblStudent.StudentName, tblStudent.Username" & _
" FROM tblStudent s" & _
" INNER JOIN [tblClasses/Students] cs ON s.StudentID = cs.StudentID" & _
" INNER JOIN tblClasses c ON cs.ClassID = c.ClassID" & _
" WHERE c.ClassName = ? ;"
请注意奇数表名称周围的方括号([]
)(并使用别名以避免重复)。另请注意,SQL字符串如何将占位符用于所选的类名。稍后,包括这样的选定类:
'Use the actual type and length of the database column here
sqlCommandObject.Parameters.Add("@ClassName", OleDbType.VarWChar, 30).Value = lstClasses.SelectedItem
这可以帮助事情更快地运行,还可以修复原始代码的编写方式中的巨大安全漏洞。最后,它可以将'
之类的字符用作类名的一部分,而无需任何其他特殊处理。
答案 1 :(得分:0)
由于您使用的是具有多个联接的MS Access,因此每个联接都需要用一组括号括起来,例如:
Dim strSQL AS String
strSQL = strSQL & "select "
strSQL = strSQL & " t.studentname, "
strSQL = strSQL & " t.username "
strSQL = strSQL & "from "
strSQL = strSQL & " ( "
strSQL = strSQL & " tblstudent t1 inner join [tblclasses/students] t2 on "
strSQL = strSQL & " t1.studentid = t2.studentid "
strSQL = strSQL & " ) "
strSQL = strSQL & " inner join tblclasses t3 on "
strSQL = strSQL & " t2.classid = t3.classid "
strSQL = strSQL & "where "
strSQL = strSQL & " t3.classname = @class "