SQL Injection Mitigation (6)

Try it! Writing safe code

Now it is time to write your own code! Your task is to use JDBC to connect to a database and request data from it.

Requirements:

  • connect to a database

  • perform a query on the database which is immune to SQL injection attacks

  • your query needs to contain at least one string parameter

Some tips before you start: For connecting to the database, you can simply assume the constants DBURL, DBUSER and DBPW as given. The content of your query does not matter, as long as the SQL is valid and meets the requirements. All the code you write gets inserted into the main method of a java class with the name "TestClass" that already imports java.sql.* for your.

Not creative enough to think of your own query? How about you try to retrieve the data for a user with a specific name from a fictional database table called users.

For example; following coding would compile without any error (but of course does not meet the requirements to complete this lesson).

try {
    Connection conn = null;
    System.out.println(conn);   //should output 'null'
} catch (Exception e) {
    System.out.println("Oops. Something went wrong!");
}

Use your knowledge and write some valid code from scratch in the editor window down below! (if you cannot type there it might help to adjust the size of your browser window once, then it should work):

Solution

💡 A database connection has to be surrounded by a try-catch block to handle the very common case of an error while establishing the connection. 💡 Remember to use the right kind of statement, so your code is no longer vulnerable for SQL injections. 💡 The wildcard symbol '?' in a prepared statement can be filled with the right kind of method. There exists one for every data type. 💡 Make sure to execute your statement. 💡 View the previous lesson to check back on how you can build set up a connection.

Complete the window with:

try {  
     Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPW);  
     PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE name = ?");  
     ps.setString(1, "Admin");  
     ps.executeUpdate();  
} catch (Exception e) {  
     System.out.println("Oops. Something went wrong!");  
}

Last updated