Search code examples

How to Convert from C# to Java JDBC

I have this code using C# to manipulate data in SQL Server:

using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
    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())
            //some code

How would I translate it to Java using JDBC and MySQL as the database? And can I avoid SQL injection?

My attempt:

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


  • JDBC uses ? characters as placeholders where bind variables would normally go. You must use a PreparedStatement to use ? placeholders. Then you can call setXXX methods (1-based indexes here!) to bind the variables and then execute.

    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();