Bolat Azamat, Kim Dongmin JDBC Basics Bolat Azamat, Kim Dongmin
In this lesson you will learn basics of the JDBC API Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. Database Java application JDBC Java application uses JDBC to connect to a database.
JDBC Driver Java application We need this driver JDBC Oracle JDBC Driver for Oracle Microsoft SQL JDBC Driver for Microsoft SQL Java application Native ODBC Calls JDBC MySQL JDBC Driver for MySQL PostgreSQL JDBC Driver for PostgreSQL We need this driver
I kindly suggest you to use Java 8!!! Driver download Go the page https://jdbc.postgresql.org/download.html#current and download the current version 42.2.5 PostgreSQL JDBC 4.2 Driver, 42.2.5 – for Java 8 PostgreSQL JDBC 4.1 Driver, 42.2.5.jre7 – for Java 7 PostgreSQL JDBC 4.0 Driver, 42.2.5.jre6 – for Java 6 I kindly suggest you to use Java 8!!!
Development environment In this tutorial we use Eclipse IDE You can download it from https://www.eclipse.org/downloads/ It is free and most widely used one Also give a look at Intellij IDEA Apply for student license and save $499.00 https://www.jetbrains.com/student/
Create project File -> New -> Java Project Set project name as you want JRE – set your java 8 environment Press Finish
Project-> Properties Registering driver 1. 2. 3. Project-> Properties Drag and drop your downloaded jar to project folder Java Build Path -> Libraries -> Add JARs.. -> your file -> OK
Create main class src -> New -> Class Input any name you want and press Finish
Let’s check did you register driver public class HelloJDBC { public static void main(String[] args) { try { Class.forName("org.postgresql.Driver"); System.out.println(”Driver registered."); } catch (ClassNotFoundException e) { System.out.println("You didn't register driver"); } You should get the following output: Driver registered.
Connection to database DriverManager is java class, basic service for managing a JDBC drivers, it has the following method: getConnection(String url, String user, String password); url – database url user – database user password – database password url Connection con = DriverManager.getConnection(”jdbc:postgresql://localhost/jdbc_basics”, “postgres”, “zxc123”); IP address database name user password
Connection to database Add this code: //get connection Connection con = null; //initialize variable try { con = DriverManager.getConnection("jdbc:postgresql://localhost/jdbc_basics", "postgres", "zxc123"); System.out.println("Successfully connected."); } catch (SQLException e) { System.out.println("Problem with your connection"); } You should get the following output: Driver registered. Successfully connected.
Executing SQL Statements Statement – interface contains functions for executing SQL commands. Statement stmt = con.createStatement(); Executing SQL instructions can be done through the use of three methods: 1. executeQuery(); - for SELECT instructions; 2. executeUpdate(); - for updating the data or the database structure; 3. execute(); - can be used for both cases when result is unknown;
Creating the table To create table with students, we need to make SQL query : CREATE TABLE IF NOT EXISTS students( student_id SERIAL, name varchar(30), score numeric )
Run query Let’s use the execute() method to add a students table to our database: stmt = con.createStatement(); String tableSql = "CREATE TABLE IF NOT EXISTS students(\n" + " student_id SERIAL, \n" + " name varchar(30),\n" + " score numeric\n" + ")"; stmt.execute(tableSql);
Insert into a table Let’s insert a row into our table, using following SQL: INSERT INTO students(name, score) VALUES('dongmin', 50.0); Next, let’s add a record to our table using the executeUpdate() method: String insertSql = "INSERT INTO students(name, score) VALUES('dongmin', 50.0);"; stmt.executeUpdate(insertSql);
Select from a table We can retrieve the records from the table using the executeQuery() method which returns an object of type ResultSet: String selectSql = "SELECT * FROM students"; ResultSet resultSet = stmt.executeQuery(selectSql); while(resultSet.next()) { System.out.println("Name: " + resultSet.getString("name")+ " Score: " +resultSet.getDouble("score")); }
PreparedStatements 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 students table based on given parameters: String updatePositionSql = "UPDATE students SET score=? WHERE student_id=?"; PreparedStatement pstmt = con.prepareStatement(updatePositionSql); 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.setDouble(1, 99.0); 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();
Update table //update table String updatePositionSql = "UPDATE students SET score=? WHERE student_id=?"; PreparedStatement pstmt = con.prepareStatement(updatePositionSql); pstmt.setDouble(1, 99.0); //set new score pstmt.setInt(2, 1); //where student_id equal to 1 int rowsAffected = pstmt.executeUpdate(); System.out.println("User update, rows affected: "+rowsAffected);
Delete record from the table Delete record is also action of updating table! //delete record String deleteRecord = "DELETE from students WHERE student_id=?"; pstmt = con.prepareStatement(deleteRecord); pstmt.setInt(1, 1); rowsAffected = pstmt.executeUpdate(); System.out.println("User deleted, rows affected: "+rowsAffected);
Delete whole table Drop table from database, be carefully this action is irreversible! //delete whole table String drop = "DROP TABLE students;"; stmt.executeUpdate(drop);
Close your connection When you finished all your operations with database, please close your connection! con.close(); Releases Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
Thank you for your attention! Further readings: - Official Java documentation: https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html - Nice and easy tutorials on JAVA JDBC: https://www.tutorialspoint.com/jdbc/