2013-04-24 65 views
0

我正在爲一個在線表單項目工作,我似乎無法找到如何從SQL數據庫獲取值並根據字符串驗證它,在數據庫= A和TextBox.text Q1 = ASQL數據庫驗證字符串

下面是到目前爲止我的代碼,但似乎無法工作,在這個有些變量是全球性的,

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

這是什麼(數據庫)? – 2013-04-24 10:29:22

+0

(數據庫)是我不能縫編程的代碼,所以我刪除了它,這樣有人可以更容易編程一些東西 – 2013-04-24 10:31:24

回答

0

您可以使用DataReader檢索價值,像(空氣代碼,因爲我沒有任何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() 

我會根據你正在尋找這個問題的具體ID刪除LIKE,而是查詢。這意味着可能將問題ID存儲在表單上。我也會參數化查詢,而不是將其構建爲字符串;否則您將面臨潛在的SQL注入攻擊。

+0

Hello Simon,對不起,我在午休時間很長的延遲。這行SqlDataReader myReader = myCommand.ExecuteReader() 根本不工作,只是出現錯誤說生成方法sub謝謝你的幫助 – 2013-04-24 12:11:05

+0

糟糕的是,這是c#語法,編輯答案。正如我所說,自從我編寫任何VB以來已經很長時間了!你可能需要修復一些錯別字。 – Simon 2013-04-24 14:59:33

+0

嗨西蒙,沒關係,謝謝你的幫助,但那裏接縫是一個錯誤離開我的命令沒有宣佈。請指教? – 2013-04-24 15:24:31