Lab6 Guide
Lab6 Guide
Lab6 Guide
I. Prerequisites
- Same as Lab 5 prerequisites
- Your Lab 5 IntelliJ IDEA’s project folder
II. Lab Setup & Guide
1. Preventing SQL Injection – Parameterized Query Approach.
- Recall the code for using Java to perform a query operation to the SQL Database.
public static void showQuery(String txtQuery) {
Connection con = null;
PreparedStatement stmt;
ResultSet rs;
try {
con = DriverManager.getConnection(connectionUrl);
stmt = con.prepareStatement(txtQuery);
rs = stmt.executeQuery();
- Examine these questions again and answer them to familiarize yourself with the above
code
1. What is a Connection, PreparedStatement, and ResultSet variable type? Find out
some of the methods they provided.
2. The method executeQuery() is used to query the database. Find the corresponding
method in PreparedStatement to perform the manipulation operation to the database
engine.
3. What if a user inputs a malicious SQL Query inside an input box? Could you explain
some of the consequences of this action?
- Luckily, experts have developed many mitigations to prevent the above attack (SQL
Injection). One is the so-called Parameterized Query, as the query text is parameterized
and only accepts user input after it validates them as safe. Here is an example code of
using parameterized query in Java code.
public static String showQuery(String txtCond) {
Connection con = null;
PreparedStatement stmt;
ResultSet rs;
String result = "";
try {
con = DriverManager.getConnection(connectionUrl);
String preparedQuery =
"""
SELECT *
FROM Student
WHERE StudentID = ?""";
stmt = con.prepareStatement(preparedQuery);
stmt.setString(1, txtCond);
rs = stmt.executeQuery();
while (rs.next()) {
result = rs.getString("StudentName");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
closeConnect(con);
}
return result;
}
- Notice the use of preparedQuery with the SQL Query and the? mark to replace the user
input. From then on, we can use stmt.setString() for Java to validate the input and
complete the query. This way, the malicious code cannot be executed and produce bad
consequences to the database.
2. Set up the helper ConnectSQL.java class.
- Below the previous methods from this class, copy and replace the <?> with your answer
to complete the following code and perform the tasks below.
- This is an Insert operation code to let Java send the query to our database engine.
public static boolean insertData(<?>) {
Connection con = null;
PreparedStatement stmt;
int rs;
boolean isUpdated = false;
try {
con = DriverManager.getConnection(connectionUrl);
con.setAutoCommit(<?>);
String insertString = <?>;
stmt = con.<?>(insertString);
stmt.<?>(1, <?>);
rs = stmt.<?>();
if (<?>) {
isUpdated = true;
}
con.commit();
} catch (SQLException e) {
return isUpdated;
} finally {
closeConnect(con);
}
return <?>;
}
@Override
protected void done() {
<?>.setEnabled(true);
}
};
worker.execute();
}
});