JAVA Development: Databases - JDBC, Connection Pools, Transactions, SQL Injection
JAVA Development: Databases - JDBC, Connection Pools, Transactions, SQL Injection
JAVA Development: Databases - JDBC, Connection Pools, Transactions, SQL Injection
JDBC helps you write Java applications that perform these three activities:
//...
connection = DriverManager.getConnection(
"jdbc:mysql://159.69.118.199/wantsome_java6", //<- url
"wantsome_java6", //<- user
"zWEq#16V"); //<- password
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM countries");
while (resultSet.next()) {
int a = resultSet.getInt("a");
String b = resultSet.getString("b");
float c = resultSet.getFloat("c");
//...
}
JDBC – Connections (1)
1. Class.forName() - dynamically load the driver's class file into memory, which
automatically registers it
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
JDBC – Connections (2)
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(myDriver);
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
JDBC – Connections (2)
● getConnection(String url)
• Don’t forget to close your connection to the database when finishing using it!!
• If you don’t use try-with-resources, you must manually call the close() method:
if (connection != null) {
connection.close();
}
JDBC – Statements
• Statement - Useful when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.
• PreparedStatement - Use the when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input parameters at runtime.
• CallableStatement - Use the when you want to access the database stored
procedures. The interface can also accept runtime input parameters.
JDBC – Statement vs PreparedStatement
statement = connection.createStatement();
String sql = "UPDATE employees SET salary=50 WHERE employee_id=100";
int rows = statement.executeUpdate(sql);
System.out.println("Rows impacted : " + rows);
VS
● Statement -> will always proceed through the four steps above for each SQL
query sent to the database (even if it’s the same exact query!)
● PreparedStatement -> pre-executes steps (1) - (3) in the execution process
above, thus saving time on repeated execution of the ‘same’ query (same SQL,
but possibly with different values for ‘?’ parameters)
JDBC – CallableStatement
In computer programming, Create, Read, Update and Delete (CRUD) are the four
basic functions of persistent storage.
● Data Transfer Object (DTO) = an object that carries data between processes
● Examples: some classes we used until now in our course - Person, Dog, etc;
classes that generally hold only state, but don’t provide behavior
Working with data
● the DAO provides specific data operations without exposing database details
● the main purpose of a DAO is to separate two major layers of the application:
the business and database (persistence) layer
● this separation allows to change database systems for applications without
needing to change the logic
Connection Pooling
Connection pooling is similar to any other object pooling, which in itself is a design
pattern.
Why use object pooling when the JVM performance for creating new objects has
been multiplied manifold?
Because there are still a few heavy objects, for which creation is still costly:
● database connection objects,
● parser objects,
● thread creation etc.
Connection Pooling
The Object Pool Pattern says "to reuse the objects that are expensive to create".
When an object is taken from the pool, it is not available in the pool until it is put back.
● Most effective in a situation when the rate of initializing a class instance is high.
● It manages the connections and provides a way to reuse and share them.
● It can also limit the maximum number of objects that can be created.
Connection Pooling
Connection pooling - it helps reduce the number of connections kept open by the database,
speeding up all the connections and improving application and database performance.
- Instead of the old way, where you would need to open a connection each time you make
a request to the DB, connection pooling, pools, the connections to the DB are recycled,
greatly reducing the number that must be opened.
- The pooler maintains ownership of the physical connection with the DB by keeping a set
of them active and alive. Whenever a user calls on a connection, the pooler searches for
an available connection, using that one rather than opening a new one. When the
application calls to close the connection, that connection is instead returned to the pool of
connections.
Connection Pooling
Transactions
Transaction example:
● Insert a row in the Orders table
● Insert a row in the Invoices table
● Insert a row in the Shipments table
● Update the balance of a user in UserBalances
● Delete a row in the Cart table
● Delete several rows in the CartItems table
What happens if our applications crashes before executing the 4th operation?
● Nothing! The whole transaction will be rolled-back!
Transactions
● Reminder: a sequence of database operations that satisfies the ACID properties is called
a transaction; this group of operations can be viewed as a single logical operation
● For example, a transfer of funds from one bank account to another, even involving
multiple changes such as debiting one account and crediting another, is a single
transaction.
○ To have a better idea, imagine what would happen the money would be taken from
the source account but never reached the destination account...
Transactions - ACID
● Consistency: ensures that a transaction can only bring the database from one
valid state to another - any data written to the database must be valid according
to all defined rules, including constraints, cascades, triggers, and any
combination thereof. This prevents database corruption by an illegal
transaction, but does not guarantee that a transaction is correct.
Transactions - ACID
• SQL injection is a code injection technique that might destroy your database
• SQL injection is one of the most common web hacking techniques
• SQL injection is the placement of malicious code in SQL statements, via web
page input
• To protect a web site from SQL injection, you can use SQL parameters
• SQL parameters are values that are added to an SQL query at execution time, in a
controlled manner