You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Once we have obained a statement, we can obtain a result by using .executeStatement(String sqlCommand)
The sql command can be update/insert/delete
Here is an example@
Statementstmt = conn.createStatement();
intresult = stmt.executeUpdate(
"INSERT INTO species VALUES (10, 'Deer', 3)");
System.out.println(result); // 1// ^^^^^ 1 is the number of rows affectedresult = stmt.executeUpdate(
"UPDATE species SET name = '' WHERE name = 'None'");
System.out.println(result); // 1result = stmt.executeUpdate(
"DELETE FROM species WHERE id = 10");
System.out.println(result); // 1
🟥 SELECT using executeQuery()
In order to run a SELECT statement and obtain a ResultSet, you need to use .executeQuery(String sqlCommand)
E.g.:
ResultSetrs = stmt.executeQuery("SELECT * FROM species");
🟥 Using execute()
The third method we can perform on a statement is .execute(String sqlCommand). The method returns true if a ResultSet can be extracted, otherwise an non select query was ran:
Statementstmt = conn.createStatement();
booleanisResultSet = stmt.execute(sql);
if (isResultSet) {
ResultSetrs = stmt.getResultSet();
System.out.println("A query was ran");
} else {
intresult = stmt.getUpdateCount();
System.out.println("An update was ran");
}
🟥 The Importance of PreparedStatement
In real life, you should use a subclass of Statement: PreparedStatement
This class has the following benefits:
Performance - PreparedStatement will figure out a plan to run the SQL efficiently
Security - can prevent SQL injection as JDBC can handle escaped quotes:
PreparedStatementps = conn.prepareStatement("delete from animal where name=?");
ps.setString(1, name);
ps.execute();
Readability - do not need to deal with string concatenation