Pengantar JDBC

Java Top

Saya baru saja mengumumkan kursus Learn Spring baru , yang berfokus pada dasar-dasar Spring 5 dan Spring Boot 2:

>> LIHAT KURSUSnya

1. Ikhtisar

Pada artikel ini, kita akan melihat JDBC (Java Database Connectivity) yang merupakan API untuk menghubungkan dan menjalankan kueri pada database.

JDBC dapat bekerja dengan database apapun selama driver yang tepat disediakan.

2. Driver JDBC

Pengandar JDBC adalah implementasi API JDBC yang digunakan untuk menghubungkan ke jenis database tertentu. Ada beberapa jenis driver JDBC:

  • Tipe 1 - berisi pemetaan ke API akses data lain; contohnya adalah driver JDBC-ODBC
  • Tipe 2 - adalah implementasi yang menggunakan pustaka sisi klien dari database target; juga disebut driver API asli
  • Tipe 3 - menggunakan middleware untuk mengubah panggilan JDBC menjadi panggilan khusus database; juga dikenal sebagai driver protokol jaringan
  • Tipe 4 - terhubung langsung ke database dengan mengubah panggilan JDBC menjadi panggilan khusus database; dikenal sebagai driver protokol database atau driver tipis,

Jenis yang paling umum digunakan adalah tipe 4, karena memiliki keuntungan karena tidak bergantung pada platform . Menghubungkan langsung ke server database memberikan kinerja yang lebih baik dibandingkan dengan jenis lainnya. Kelemahan dari jenis driver ini adalah spesifik database - mengingat setiap database memiliki protokol spesifiknya sendiri.

3. Menghubungkan ke Database

Untuk terhubung ke database, kita hanya perlu menginisialisasi driver dan membuka koneksi database.

3.1. Mendaftarkan Pengemudi

Sebagai contoh, kami akan menggunakan driver protokol database tipe 4.

Karena kami menggunakan database MySQL, kami memerlukan dependensi mysql-connector-java :

 mysql mysql-connector-java 6.0.6 

Selanjutnya, mari daftarkan driver menggunakan metode Class.forName () , yang secara dinamis memuat kelas driver:

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

Dalam versi JDBC yang lebih lama, sebelum mendapatkan koneksi, pertama-tama kita harus menginisialisasi driver JDBC dengan memanggil metode Class.forName . Mulai JDBC 4.0, semua driver yang ditemukan di classpath secara otomatis dimuat . Oleh karena itu, kita tidak memerlukan bagian Class.forName ini di lingkungan modern.

3.2. Membuat Koneksi

Untuk membuka koneksi, kita bisa menggunakan metode getConnection () dari kelas DriverManager . Metode ini membutuhkan parameter String URL koneksi :

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

Karena Connection adalah sumber daya AutoCloseable , kita harus menggunakannya di dalam blok coba-dengan-sumber daya .

Sintaks dari URL koneksi tergantung pada tipe database yang digunakan. Mari kita lihat beberapa contoh:

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

Untuk terhubung ke database myDb yang ditentukan , kita harus membuat database dan pengguna, dan menambahkan akses yang diperlukan:

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

4. Menjalankan Pernyataan SQL

Mengirim instruksi SQL ke database, kita dapat menggunakan contoh tipe Statement , PreparedStatement, atau CallableStatement, yang bisa kita peroleh menggunakan objek Connection .

4.1. Pernyataan

The Pernyataan antarmuka berisi fungsi penting untuk mengeksekusi perintah SQL.

Pertama, mari buat objek Pernyataan :

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

Sekali lagi, kita harus bekerja dengan Pernyataan di dalam blok coba-dengan-sumber daya untuk pengelolaan sumber daya otomatis.

Bagaimanapun, menjalankan instruksi SQL dapat dilakukan melalui penggunaan tiga metode:

  • executeQuery () untuk instruksi SELECT
  • executeUpdate () untuk memperbarui data atau struktur database
  • execute () dapat digunakan untuk kedua kasus di atas jika hasilnya tidak diketahui

Mari gunakan metode execute () untuk menambahkan tabel siswa ke database kita:

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);

Saat menggunakan metode execute () untuk memperbarui data, maka metode stmt.getUpdateCount () mengembalikan jumlah baris yang terpengaruh.

Jika hasilnya 0 maka tidak ada baris yang terpengaruh, atau itu adalah perintah pembaruan struktur database.

Jika nilainya -1, maka perintahnya adalah query SELECT; kita kemudian bisa mendapatkan hasilnya menggunakan stmt.getResultSet () .

Selanjutnya, mari tambahkan record ke tabel kita menggunakan metode 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();

Namun, jika kita menggunakan sumber daya dalam blok coba-dengan-sumber daya , kita tidak perlu memanggil metode close () secara eksplisit, karena blok coba-dengan-sumber daya melakukannya untuk kita secara otomatis.

Hal yang sama berlaku untuk Pernyataan s, PreparedStatement s, CallableStatement s, dan ResultSet s.

9. Kesimpulan

Dalam tutorial ini, kami telah melihat dasar-dasar bekerja dengan JDBC API.

Seperti biasa, kode sumber lengkap dari contoh dapat ditemukan di GitHub.

Jawa bawah

Saya baru saja mengumumkan kursus Learn Spring baru , yang berfokus pada dasar-dasar Spring 5 dan Spring Boot 2:

>> LIHAT KURSUSnya