2012-08-07 2 views
1

mysql 데이터베이스에서 읽을 코드가 있지만 사용자가 테이블에 있는지 확인하기 위해 수정할 수있는 방법이 궁금합니다.사용자가 mysql 데이터베이스 vb.net에 있는지 확인하는 방법

감사

Private Sub GetDBData() 
    Try 
     'prepare connection query 
     strQuery = "SELECT users.Username, users.Password " & _ 
     "FROM users " & _ 
     "WHERE Username='User'" 
     SQLCmd = New MySqlCommand(strQuery, dbCon) 
     'open db and start query 
     dbCon.Open() 
     DR = SQLCmd.ExecuteReader 
     While DR.Read 
      MysqlData.Text = MysqlData.Text & DR.Item("Username") & Space(10) & DR.Item("Password") & vbCrLf 
     End While 
     'done so closing db 
     DR.Close() 
     dbCon.Close() 

    Catch ex As Exception 
     MessageBox.Show(ex.Message) 
    End Try 
End Sub 
+2

한눈에 매개 변수가있는 SQL을 사용하십시오. 당신은 SQL 주입을 위해 활짝 열려 있습니다. – Lion

답변

2

쉬운 방법은 다음과 같은 쿼리 수 있도록하는 것입니다, 당신은 그것을 실행

SELECT COUNT(*) FROM users WHERE Username='user123'; 

그것을 반환 값을 철회하고 0이면 사용자는 아무튼 존재하지 않습니다. 1 인 경우 그는 존재하고 1보다 크면 무언가가 잘못되었습니다 (동일한 사용자 이름을 가진 사용자가 두 명 이상 있습니다).

2

내 VB는 꽤 녹슬었지만 여기에는 그 주안점이 있습니다.

Private Sub GetDBData() 
Try 
    'prepare connection query 
    strQuery = "SELECT users.Username, users.Password " & _ 
    "FROM users " & _ 
    "WHERE Username='User'" 
    SQLCmd = New MySqlCommand(strQuery, dbCon) 
    'open db and start query 
    dbCon.Open() 
    DR = SQLCmd.ExecuteReader 

    If DR.HasRows Then 

     While DR.Read 
      MysqlData.Text = MysqlData.Text & DR.Item("Username") & Space(10) & DR.Item("Password") & vbCrLf 
     End While 
    Else 
     'COMMENT: Your user didn't exist 
    End If 

    'done so closing db 

    'COMMENT: move to a finally() section and check objects are not null before closing 
    DR.Close() 
    dbCon.Close() 

Catch ex As Exception 
    MessageBox.Show(ex.Message) 
End Try 

최종 하위 parameters

2

사용 command는 SQL 주입을 방지 할 수 있습니다. 약간의 비교를 수행하여 사용자 이름 존재 여부 만 확인하려는 경우 해당 에 대한 전략은 부울을 반환하는 함수를 만드는 것입니다. 아래는 여러분의 필요에 따른 예제 코드입니다.

Private Function IsUserExist(userName as string) AS Boolean 

     Dim returnValue as boolean = false 

     strQuery = "SELECT COUNT(*)" 
     strQuery &= "FROM users " 
     strQuery &= "WHERE Username = @xUserName " 

     Using xConn as new MySQLCnnection("connectionStringHere") 
      Using xComm as New MySQLCommand() 
       With xComm 
        .Connection = xConn 
        .CommandText = strQuery 
        .CommandType = CommandType.Text 
        .Parameters.AddWithValue("@xUserName", userName) 
       End With 
       Try 
        xConn.Open() 
        If CInt(xComm.ExecuteScalar()) > 0 Then 
         returnValue = true 
        End If 
       Catch ex as MySQlException 
        MsgBox(ex.Message) 
        returnValue = false 
       Finally 
        xConn.Close 
       End Try 
      End Using 
     End Using 

     return returnValue 
End Sub 
2

수정 하시겠습니까? 너무 많이 잘못했다. 블록 사용, 예외 삼킴 및 SQL 주입 공격 가능성이 없습니다.

사용하여 블록에

Private Function UserExists(argUser As string) As Bool 
    strQuery = "SELECT Username FROM users WHERE Username=?User" 
    Using SQLcmd = New MySqlCommand(strQuery, dbCon) 
    SQLCmd.Parameters.Add("?User",argUser) 
    dbCon.Open() 
    Using reader = SQLCmd.ExecuteReader() 
     return reader.Read() 
    End Using 
    End Using 
End Function 

내가 (당신이 현재 whereever에서 그것을 얻는 대신뿐만 아니라 연결을 인스턴스화 할 것 (나는 VB하지 않지만 기본적인 아이디어는 소리)와 같은

뭔가) 그것이 나일지라도.

+0

어쩌면 어리석은 질문 일지 모르지만 사용자는 무엇을 의미합니까? – user1244772

+0

매개 변수화 된 쿼리 효과적으로? 사용자는 SQL 주입 공격까지 열지 않는 방식으로 SQLCmd.Parameters.Add 호출의 값 인수로 대체됩니다. –

0
Protected Sub btnlogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlogin.Click 
    Dim myAdapter As New MySqlDataAdapter 
    Dim myCommand As New MySqlCommand 
    Dim myData As MySqlDataReader 
    Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;Database=name;User ID=root;Password=pwd;") 

    Dim loginstring As String = "SELECT uname,password,type FROM logindetails WHERE uname = '" + txtuname.Text + "' AND password = '" + txtpwd.Text + "' " 
    Try 
     conn.Open() 
    Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.) 
     MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical) 
    End Try 

    myCommand.Connection = conn 
    myCommand.CommandText = loginstring 
    myAdapter.SelectCommand = myCommand 
    myData = myCommand.ExecuteReader 

    If myData.HasRows = 0 Then 
     MsgBox("Invalid Credentials", MsgBoxStyle.Critical) 
    Else 
     Response.Redirect("Adminhome.aspx") 
     MsgBox("Logged in as " & txtuname.Text & ".", MsgBoxStyle.Information) 
    End If 
    conn.Close() 
End Sub 
+0

코드 전용 솔루션 만 제공하면 안됩니다. –

관련 문제