在VB中工作,我连接到访问数据库,需要从表中获取值。
user = Environment.UserName
command.CommandText = "SELECT 'nid', 'UserName' FROM qryUSERJOBS WHERE UserName = " & user
command.Connection = connect
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
record = reader("nid").ToString
End While
End Using
当我的代码进入Using
语句时,会创建阅读器,并且会立即显示我的获胜表单,而无需读取数据库或点击包含它的例程的End Sub
。有什么想法吗?
答案 0 :(得分:3)
Using connect As New OleDbConnection(connectionString)
connect.Open()
Using command As New SqlCommand(
"SELECT nid, UserName FROM qryUSERJOBS WHERE UserName = @user",
connect)
user = Environment.UserName
command.Parameters.Add(New OleDbParameter("@user", user))
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
record = reader("nid").ToString
End While
End Using
End Using
End Using
答案 1 :(得分:-1)
将代码放入Try ... Catch块后,我的参数出错了。我需要在user
变量周围添加单引号。
代码已修复:
user = Environment.UserName
command.CommandText = "SELECT nid, UserName FROM qryUSERJOBS WHERE UserName = '" & user & "'"
command.Connection = connect
connect.Open()
Try
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
record = reader("nid").ToString
End While
End Using
Catch ex As Exception
End Try
感谢大家的帮助和建议!