JAVA Development: Databases - JDBC, Connection Pools, Transactions, SQL Injection

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

JAVA Development

Databases - JDBC, Connection pools,


Transactions, SQL Injection
JDBC - Java Database Connectivity

JDBC helps you write Java applications that perform these three activities:

● Connect to a data source, like a database


● Send queries and update statements to the database
● Retrieve & process the data received from DB as the result of your query
JDBC - Java Database Connectivity

• JDBC provides a common interface allowing to perform SQL operations


independent of the exact type of the used database

• To use JDBC with a particular database, you’ll also need a specific


implementation of the JDBC driver for that database
JDBC - Java Database Connectivity

//...
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)

2. DriverManager.registerDriver() - if you are using a non-JDK compliant JVM,


such as the one provided by Microsoft

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)

String url = "jdbc:oracle:thin:user/pswd@hostName:1521:DBName";


Connection conn = DriverManager.getConnection(url);

● getConnection(String url, Properties prop)

String url = "jdbc:oracle:thin@hostName:1521:DBName";


Properties info = new Properties();
info.put("user", "username-here");
info.put("password", "password-here");
Connection conn = DriverManager.getConnection(url, info);

● getConnection(String url, String user, String password)


JDBC – Connections (2)

RDBMS JDBC driver name URL format

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port:databaseName

DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port/databaseName

Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname:port/databaseName


JDBC – Connections - close

• 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

String sql = "UPDATE employees SET salary=? WHERE employee_id=100";


preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(50, salary);
int rows = preparedStatement.executeUpdate();
System.out.println("Rows impacted : " + rows);
JDBC – Statement vs PreparedStatement

Most relational databases handles a JDBC / SQL query in four steps:

1. Parse the incoming SQL query


2. Compile the SQL query
3. Plan/optimize the data acquisition path
4. Execute the optimized query / acquire and return data

● 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

String sql = "{? = call getEmpName (?)}";


CallableStatement callable = connection.prepareCall(sql);
callable.registerOutParameter(1, Types.INTEGER);
callable.setString(2, "param1");
ResultSet rs = callable.executeQuery();
//…

● callable statements are used to call on stored procedures


● can have both in and out parameters (and also inout…)
CRUD

In computer programming, Create, Read, Update and Delete (CRUD) are the four
basic functions of persistent storage.

Operations SQL HTTP


CREATE INSERT PUT/POST

READ SELECT GET

UPDATE UPDATE PUT/POST/PATCH

DELETE DELETE DELETE


Working with data

● Data Transfer Object (DTO) = an object that carries data between processes

○ Used only to aggregate and transfer data (composed of various parts)


between systems in one call, instead of multiple calls (avoiding the
possibly VERY expensive overhead)
○ They are simple objects that should not contain any business logic (but
may contain serialization and deserialization mechanisms)

● 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

● Data Access Object (DAO) = an object that provides an abstract interface to


some type of database or other persistence mechanism.

● 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".

An Object pool is a container for a specific type of objects.

When an object is taken from the pool, it is not available in the pool until it is put back.

Objects in the pool have a life cycle:


● creation,
● validation,
● destruction.
Connection Pooling

Advantages of the Object Pool design pattern:

● It boosts the performance of the application significantly.

● 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

A database transaction consists of a group of operations performed on the


database.

The operations will either be


● all successful: transaction is committed, all operations performed
● all cancelled: transaction is rolled back and the database will get back to the
initial state
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

Connection dbConnection = null;


try {
dbConnection.setAutoCommit(false); //<– Disable auto commit mode
...
s1.executeUpdate();
s2.executeUpdate();
dbConnection.commit(); //<– Commits the transaction
} catch (Exception ex) {
dbConnection.rollback(); //<– Rollback if error appears
} finally {
dbConnection.close(); //<– Make sure to also close it
}
Transactions - ACID

● In computer science, ACID (Atomicity, Consistency, Isolation, Durability) is a set of


properties of database transactions intended to guarantee validity even in the event of
errors, power failures, etc.

● 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

● Atomicity: guarantees that each transaction is treated as a single "unit", which


either succeeds completely, or fails completely - if any of the statements
constituting a transaction fails to complete, the entire transaction fails and the
database is left unchanged. An atomic system must guarantee atomicity in
each and every situation, including power failures, errors and crashes.

● 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

● Isolation: transactions are often executed concurrently (e.g., reading and


writing to multiple tables at the same time). Isolation ensures that concurrent
execution of transactions leaves the database in the same state that would
have been obtained if the transactions were executed sequentially.

● Durability: guarantees that once a transaction has been committed, it will


remain committed even in the case of a system failure (e.g., power outage or
crash). This usually means that completed transactions (or their effects) are
recorded in non-volatile memory.
SQL Injection

• 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

String txtUserId = getRequestString("UserId");


String txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

"SELECT * FROM Users WHERE UserId = 105 OR 1=1;" //always true


Use SQL Parameters for Protection

• 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

PreparedStatement preparedStatement = null;


try {
String SQL = " SELECT * FROM Users WHERE UserId = ? WHERE password = ?";
preparedStatement = connection.prepareStatement(SQL);
preparedStatement.setInt(1, Integer.MAX_VALUE);
preparedStatement.setString(2, "my password");
}
catch (SQLException e) {}
finally {
preparedStatement.close();
}

You might also like