从SQL结果存储ID



im运行以下代码,以判断用户是否在数据库 - 标准内容上进行区分。显然,一旦执行代码,如果有结果,将返回boolean true或false。如果找到结果,我想存储上述结果的ID。谁能告诉我ID如何做到这一点?

代码:

 Username = txtUserName.Text
    Password = txtPassword.Text
    dbConnInfo = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source = C:UsersDaveDocumentstechs.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

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

为了加载结果的ID,您需要使用sqlcommand.executescalar(),因为这经过优化以从sql中撤回一个结果。

关于您的代码有什么问题,您对SQL注入攻击开放,您应该使用我的样本中所示的参数化查询。

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

相关内容

  • 没有找到相关文章

最新更新