我正在为一个在线表单工作,我似乎无法找到如何从SQL数据库获取值并根据字符串验证它,例如数据库中的Q1 = A和TextBox.text = A
以下是我的代码到目前为止但似乎无法正常工作,其中的一些变量是全局的,
Dim Question As String = "Q" & count
Dim textVal As String = TextBox.Text
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection
Dim dbSource As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ben.miles\documents\visual studio 2012\Projects\WebTraningQuestions\WebTraningQuestions\App_Data\Usertest.mdf"
Dim ds As New DataSet
Dim sql As String = "SELECT FROM SAP"
Dim da As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(sql, conn)
conn.ConnectionString = dbSource
Dim SqSearch As String = "%" & textVal & "%"
Dim sqlQ1 As String = sql & " WHERE Questions LIKE SqSearch"
Dim cmd1 As New SqlCommand(sqlQ1, conn)
conn.Open()
'This is where I cant get my code right but if you see below. I would like it something like this.
If TextBox.Text = (database) Then
Label.Text = "Correct"
Label.ForeColor = Drawing.Color.Green
Else
Label.Text = "Wrong"
Label.ForeColor = Drawing.Color.Red
End If
答案 0 :(得分:0)
您可以使用DataReader来检索值,例如(air-code,自从我做了VB之后已经有一段时间了):
Dim Question As String = "Q" & count
Dim textVal As String = TextBox.Text
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection
Dim dbSource As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ben.miles\documents\visual studio 2012\Projects\WebTraningQuestions\WebTraningQuestions\App_Data\Usertest.mdf"
Dim ds As New DataSet
Dim sql As String = "SELECT [fields..] FROM SAP"
Dim da As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(sql, conn)
conn.ConnectionString = dbSource
Dim SqSearch As String = "%" & textVal & "%"
Dim sqlQ1 As String = sql & " WHERE Questions LIKE SqSearch"
Dim cmd1 As New SqlCommand(sqlQ1, conn)
conn.Open()
Dim myReader AS SqlDataReader = cmd1.ExecuteReader()
If myReader.HasRows Then
myReader.Read()
If TextBox.Text = (myReader.GetString(col_of_field)) Then
Label.Text = "Correct"
Label.ForeColor = Drawing.Color.Green
Else
Label.Text = "Wrong"
Label.ForeColor = Drawing.Color.Red
End If
End If
myReader.Close()
我会删除LIKE,而是根据您要查找的问题的特定ID进行查询。这意味着可能在某个地方将问题ID存储在您的表单上。我也会参数化查询而不是将其构建为字符串;除此之外,你正在打开潜在的SQL注入攻击。