2014-03-31 86 views
0

我使用C#來操縱SQL服務器從C#轉換成Java JDBC

using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString)) 
      { 
       myDatabaseConnection.Open(); 
       using (SqlCommand SqlCommand = new SqlCommand("Select * from Users where Username = @UserName and Password = @Password", myDatabaseConnection)) 
       { 
        SqlCommand.CommandType = CommandType.Text; 
        SqlCommand.Parameters.AddWithValue("@UserName", TextBox1.Text); 
        SqlCommand.Parameters.AddWithValue("@Password", TextBox2.Text); 
        SqlDataReader DR1 = SqlCommand.ExecuteReader(); 
        if (DR1.Read()) 
        { 
        //somecodes 
        } 
       } 
      } 

我怎麼會它使用JDBC和MySQL作爲數據庫轉換爲Java數據驗證碼?並且可以避免SQL注入。

試用:

try (Connection conn = DriverManager.getConnection(dbURL, username, password)) { 
      String sql = "Select * from Users where Username = @UserName and Password = @Password"; 
      Statement statement = conn.createStatement(); 
      //parameters? 
      ResultSet result = statement.executeQuery(sql); 
      while (result.next()){ 
       //somecode 
      } 

     } catch (SQLException ex) { 
      ex.printStackTrace(); 
     } 

回答

0

JDBC使用?字符作爲佔位符綁定變量通常會去。您必須使用PreparedStatement才能使用?佔位符。然後你可以調用setXXX方法(這裏是基於1的索引!)來綁定變量然後執行。

String sql = "Select * from Users where Username = ? and Password = ?"; 
PreparedStatement pStatement = conn.prepareStatement(sql); 
pStatement.setString(1, username); 
pStatement.setString(2, password); 
ResultSet rs = statement.executeQuery(); 
+0

DataReader.Read()是否等同於result.next()? –

+0

從我在網上可以告訴的有關'SqlDataReader'的'Read()'(我不是C#人),它似乎等同於ResultSet的'next()'方法。如果有下一條記錄,它將前進到下一條記錄並返回一個「boolean」。 – rgettman