Въведение в JDBC

Java Top

Току що обявих новия курс Learn Spring , фокусиран върху основите на Spring 5 и Spring Boot 2:

>> ПРЕГЛЕД НА КУРСА

1. Общ преглед

В тази статия ще разгледаме JDBC (Java Database Connectivity), който е API за свързване и изпълнение на заявки в база данни.

JDBC може да работи с всяка база данни, стига да са осигурени подходящи драйвери.

2. JDBC драйвери

JDBC драйверът е реализация на JDBC API, използвана за свързване към определен тип база данни. Има няколко типа JDBC драйвери:

  • Тип 1 - съдържа картографиране към друг API за достъп до данни; пример за това е JDBC-ODBC драйверът
  • Тип 2 - е изпълнение, което използва клиентски библиотеки на целевата база данни; наричан още драйвер за нативен API
  • Тип 3 - използва междинен софтуер за конвертиране на JDBC повиквания в повиквания, специфични за база данни; известен също като драйвер за мрежов протокол
  • Тип 4 - свържете се директно с база данни чрез преобразуване на JDBC повиквания в повиквания, специфични за база данни; известни като драйвери за протокол на база данни или тънки драйвери,

Най-често използваният тип е тип 4, тъй като има предимството да бъде независим от платформата . Свързването директно със сървър на база данни осигурява по-добра производителност в сравнение с други типове. Недостатъкът на този тип драйвери е, че е специфичен за базата данни - като се има предвид, че всяка база данни има свой специфичен протокол.

3. Свързване към база данни

За да се свържем с база данни, просто трябва да инициализираме драйвера и да отворим връзка с база данни.

3.1. Регистрация на драйвера

За нашия пример ще използваме драйвер за протокол от база данни тип 4.

Тъй като използваме база данни MySQL, се нуждаем от зависимостта mysql-connector-java :

 mysql mysql-connector-java 6.0.6 

След това нека регистрираме драйвера, използвайки метода Class.forName () , който динамично зарежда класа на драйвера:

Class.forName("com.mysql.cj.jdbc.Driver");

В по-старите версии на JDBC, преди да получим връзка, първо трябваше да инициализираме драйвера на JDBC, като извикаме метода Class.forName . От JDBC 4.0 всички драйвери, които се намират в пътя на класа, се зареждат автоматично . Следователно, ние няма да се нуждаем от тази част Class.forName в съвременните среди.

3.2. Създаване на връзка

За да отворим връзка, можем да използваме метода getConnection () на класа DriverManager . Този метод изисква параметър на низ URL за връзка :

try (Connection con = DriverManager .getConnection("jdbc:mysql://localhost:3306/myDb", "user1", "pass")) { // use con here }

Тъй като Връзката е ресурс с автоматично затваряне , трябва да я използваме в блока try-with-resources .

Синтаксисът на URL адреса на връзката зависи от типа на използваната база данни. Нека да разгледаме няколко примера:

jdbc:mysql://localhost:3306/myDb?user=user1&password=pass
jdbc:postgresql://localhost/myDb
jdbc:hsqldb:mem:myDb

За да се свържем с посочената база данни myDb , ще трябва да създадем базата данни и потребител и да добавим необходимия достъп:

CREATE DATABASE myDb; CREATE USER 'user1' IDENTIFIED BY 'pass'; GRANT ALL on myDb.* TO 'user1';

4. Изпълнение на SQL изявления

Изпращаме SQL инструкции към базата данни, ние можем да използваме екземпляри от тип Statement , PreparedStatement или CallableStatement, които можем да получим с помощта на обекта Connection .

4.1. Изявление

Интерфейсът на изявлението съдържа основните функции за изпълнение на SQL команди.

Първо, нека създадем Statement обект:

try (Statement stmt = con.createStatement()) { // use stmt here }

Отново трябва да работим с Statement s вътре в блок try-with-resources за автоматично управление на ресурсите.

Както и да е, изпълнението на SQL инструкции може да стане чрез използването на три метода:

  • executeQuery () за инструкции SELECT
  • executeUpdate () за актуализиране на данните или структурата на базата данни
  • execute () може да се използва и за двата случая по-горе, когато резултатът е неизвестен

Нека използваме метода execute () , за да добавим студентска таблица към нашата база данни:

String tableSql = "CREATE TABLE IF NOT EXISTS employees" + "(emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30)," + "position varchar(30), salary double)"; stmt.execute(tableSql);

Когато използвате метода execute () за актуализиране на данните, методът stmt.getUpdateCount () връща броя на засегнатите редове.

Ако резултатът е 0, тогава не са засегнати нито редове, или е команда за актуализиране на структурата на базата данни.

Ако стойността е -1, тогава командата е била заявка SELECT; след това можем да получим резултата с помощта на stmt.getResultSet () .

След това нека добавим запис към нашата таблица, използвайки метода executeUpdate () :

String insertSql = "INSERT INTO employees(name, position, salary)" + " VALUES('john', 'developer', 2000)"; stmt.executeUpdate(insertSql);

The method returns the number of affected rows for a command that updates rows or 0 for a command that updates the database structure.

We can retrieve the records from the table using the executeQuery() method which returns an object of type ResultSet:

String selectSql = "SELECT * FROM employees"; try (ResultSet resultSet = stmt.executeQuery(selectSql)) { // use resultSet here }

We should make sure to close the ResultSet instances after use. Otherwise, we may keep the underlying cursor open for a much longer period than expected. To do that, it's recommended to use a try-with-resources block, as in our example above.

4.2. PreparedStatement

PreparedStatement objects contain precompiled SQL sequences. They can have one or more parameters denoted by a question mark.

Let's create a PreparedStatement which updates records in the employees table based on given parameters:

String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?"; try (PreparedStatement pstmt = con.prepareStatement(updatePositionSql)) { // use pstmt here }

To add parameters to the PreparedStatement, we can use simple setters – setX() – where X is the type of the parameter, and the method arguments are the order and value of the parameter:

pstmt.setString(1, "lead developer"); pstmt.setInt(2, 1);

The statement is executed with one of the same three methods described before: executeQuery(), executeUpdate(), execute() without the SQL String parameter:

int rowsAffected = pstmt.executeUpdate();

4.3. CallableStatement

The CallableStatement interface allows calling stored procedures.

To create a CallableStatement object, we can use the prepareCall() method of Connection:

String preparedSql = "{call insertEmployee(?,?,?,?)}"; try (CallableStatement cstmt = con.prepareCall(preparedSql)) { // use cstmt here }

Setting input parameter values for the stored procedure is done like in the PreparedStatement interface, using setX() methods:

cstmt.setString(2, "ana"); cstmt.setString(3, "tester"); cstmt.setDouble(4, 2000);

If the stored procedure has output parameters, we need to add them using the registerOutParameter() method:

cstmt.registerOutParameter(1, Types.INTEGER);

Then let's execute the statement and retrieve the returned value using a corresponding getX() method:

cstmt.execute(); int new_id = cstmt.getInt(1);

For example to work, we need to create the stored procedure in our MySql database:

delimiter // CREATE PROCEDURE insertEmployee(OUT emp_id int, IN emp_name varchar(30), IN position varchar(30), IN salary double) BEGIN INSERT INTO employees(name, position,salary) VALUES (emp_name,position,salary); SET emp_id = LAST_INSERT_ID(); END // delimiter ;

The insertEmployee procedure above will insert a new record into the employees table using the given parameters and return the id of the new record in the emp_id out parameter.

To be able to run a stored procedure from Java, the connection user needs to have access to the stored procedure's metadata. This can be achieved by granting rights to the user on all stored procedures in all databases:

GRANT ALL ON mysql.proc TO 'user1';

Alternatively, we can open the connection with the property noAccessToProcedureBodies set to true:

con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass");

This will inform the JDBC API that the user does not have the rights to read the procedure metadata so that it will create all parameters as INOUT String parameters.

5. Parsing Query Results

After executing a query, the result is represented by a ResultSet object, which has a structure similar to a table, with lines and columns.

5.1. ResultSet Interface

The ResultSet uses the next() method to move to the next line.

Let's first create an Employee class to store our retrieved records:

public class Employee { private int id; private String name; private String position; private double salary; // standard constructor, getters, setters }

Next, let's traverse the ResultSet and create an Employee object for each record:

String selectSql = "SELECT * FROM employees"; try (ResultSet resultSet = stmt.executeQuery(selectSql)) { List employees = new ArrayList(); while (resultSet.next()) { Employee emp = new Employee(); emp.setId(resultSet.getInt("emp_id")); emp.setName(resultSet.getString("name")); emp.setPosition(resultSet.getString("position")); emp.setSalary(resultSet.getDouble("salary")); employees.add(emp); } }

Retrieving the value for each table cell can be done using methods of type getX() where X represents the type of the cell data.

The getX() methods can be used with an int parameter representing the order of the cell, or a String parameter representing the name of the column. The latter option is preferable in case we change the order of the columns in the query.

5.2. Updatable ResultSet

Implicitly, a ResultSet object can only be traversed forward and cannot be modified.

If we want to use the ResultSet to update data and traverse it in both directions, we need to create the Statement object with additional parameters:

stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE );

To navigate this type of ResultSet, we can use one of the methods:

  • first(), last(), beforeFirst(), beforeLast() – to move to the first or last line of a ResultSet or to the line before these
  • next(), previous() – to navigate forward and backward in the ResultSet
  • getRow() – to obtain the current row number
  • moveToInsertRow(), moveToCurrentRow() – to move to a new empty row to insert and back to the current one if on a new row
  • absolute(int row) – to move to the specified row
  • relative(int nrRows) – to move the cursor the given number of rows

Updating the ResultSet can be done using methods with the format updateX() where X is the type of cell data. These methods only update the ResultSet object and not the database tables.

To persist the ResultSet changes to the database, we must further use one of the methods:

  • updateRow() – to persist the changes to the current row to the database
  • insertRow(), deleteRow() – to add a new row or delete the current one from the database
  • refreshRow() – to refresh the ResultSet with any changes in the database
  • cancelRowUpdates() – to cancel changes made to the current row

Let's take a look at an example of using some of these methods by updating data in the employee's table:

try (Statement updatableStmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { try (ResultSet updatableResultSet = updatableStmt.executeQuery(selectSql)) { updatableResultSet.moveToInsertRow(); updatableResultSet.updateString("name", "mark"); updatableResultSet.updateString("position", "analyst"); updatableResultSet.updateDouble("salary", 2000); updatableResultSet.insertRow(); } }

6. Parsing Metadata

The JDBC API allows looking up information about the database, called metadata.

6.1. DatabaseMetadata

The DatabaseMetadata interface can be used to obtain general information about the database such as the tables, stored procedures, or SQL dialect.

Let's have a quick look at how we can retrieve information on the database tables:

DatabaseMetaData dbmd = con.getMetaData(); ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null); while (tablesResultSet.next()) { LOG.info(tablesResultSet.getString("TABLE_NAME")); }

6.2. ResultSetMetadata

This interface can be used to find information about a certain ResultSet, such as the number and name of its columns:

ResultSetMetaData rsmd = rs.getMetaData(); int nrColumns = rsmd.getColumnCount(); IntStream.range(1, nrColumns).forEach(i -> { try { LOG.info(rsmd.getColumnName(i)); } catch (SQLException e) { e.printStackTrace(); } });

7. Handling Transactions

By default, each SQL statement is committed right after it is completed. However, it's also possible to control transactions programmatically.

This may be necessary in cases when we want to preserve data consistency, for example when we only want to commit a transaction if a previous one has completed successfully.

First, we need to set the autoCommit property of Connection to false, then use the commit() and rollback() methods to control the transaction.

Let's add a second update statement for the salary column after the employee position column update and wrap them both in a transaction. This way, the salary will be updated only if the position was successfully updated:

String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?"; PreparedStatement pstmt = con.prepareStatement(updatePositionSql); pstmt.setString(1, "lead developer"); pstmt.setInt(2, 1); String updateSalarySql = "UPDATE employees SET salary=? WHERE emp_id=?"; PreparedStatement pstmt2 = con.prepareStatement(updateSalarySql); pstmt.setDouble(1, 3000); pstmt.setInt(2, 1); boolean autoCommit = con.getAutoCommit(); try { con.setAutoCommit(false); pstmt.executeUpdate(); pstmt2.executeUpdate(); con.commit(); } catch (SQLException exc) { con.rollback(); } finally { con.setAutoCommit(autoCommit); }

For the sake of brevity, we omit the try-with-resources blocks here.

8. Closing the Resources

When we're no longer using it, we need to close the connection to release database resources.

We can do this using the close() API:

con.close();

Ако обаче използваме ресурса в блок try-with-resources , не е нужно да извикваме изрично метода close () , тъй като блокът try-with-resources прави това за нас автоматично.

Същото важи и за Statement s, PreparedStatement s, CallableStatement s и ResultSet s.

9. Заключение

В този урок разгледахме основите на работата с JDBC API.

Както винаги, пълният изходен код на примерите може да бъде намерен в GitHub.

Дъно на Java

Току що обявих новия курс Learn Spring , фокусиран върху основите на Spring 5 и Spring Boot 2:

>> ПРЕГЛЕД НА КУРСА