0

我运行以下代码来判断用户是否存在于数据库中 - 标准的东西。显然,一旦代码运行,如果有结果,将返回布尔值 true 或 false。如果找到结果,我想存储所述结果的 ID。谁能告诉我我是怎么做的?

代码:

 Username = txtUserName.Text
    Password = txtPassword.Text
    dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Dave\Documents\techs.mdb"
    con.ConnectionString = dbConnInfo
    con.Open()
    Sql = "SELECT * FROM techs WHERE userName =  '" & Username & "' AND '" & Password & "'"
    LoginCommand = New OleDb.OleDbCommand(Sql, con)
    CheckResults = LoginCommand.ExecuteReader
    RowsFound = CheckResults.HasRows
    con.Close()
    If RowsFound = True Then

        MsgBox("Details found")

        TechScreen.Show()
    Else
        MsgBox("Incorrect details")
    End If
4

1 回答 1

2

您发布的代码段存在很多问题。希望我能帮助您纠正这些问题。

为了加载结果的 ID,您需要使用SqlCommand.ExecuteScalar(),因为它经过优化以从 Sql 中拉回一个结果。

至于您的代码有什么问题,您对 Sql Injection 攻击持开放态度,您应该使用参数化查询,如下面的示例所示。

Public Function AddProductCategory( _
  ByVal newName As String, ByVal connString As String) As Integer 
    Dim newProdID As Int32 = 0
    Dim sql As String = _
     "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); " _
       & "SELECT CAST(scope_identity() AS int);" 

Using conn As New SqlConnection(connString)
    Dim cmd As New SqlCommand(sql, conn)
    cmd.Parameters.Add("@Name", SqlDbType.VarChar)
    cmd.Parameters("@Name").Value = newName
    Try
        conn.Open()
        newProdID = Convert.ToInt32(cmd.ExecuteScalar())
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try 
End Using 

Return newProdID
End Function

资料来源:MSDN

于 2012-10-26T00:20:58.787 回答