Chapter 8. JDBC
ITSS Java Programming NGUYEN Hong Quang, HUT
Components of JDBC
JDBC 1
JDBC API
‘java.sql’ and ‘javax.sql’ package SQL Interfaces for application
JDBC Driver Manager
manage two or more JDBC drivers ‘DriverManager’ class in the java.sql package
JDBC
JDBC Driver API
defined for connecting between the JDBC driver
manager and JDBC drivers
JDBC Driver
access each database 4 types :
JDBCODBC bridge Native API partly – Java technologybased driver Netprotocol all Java technologybased driver Nativeprotocol Java technologybased driver
Setting classpath for JDBC
Driver class as a archive file:
classpath=% classpath %;C:\mysql\ mysql connectorjava5.1.7bin.jar;
Driver class as a directory: classpath=% classpath %;C:\mysql\classes;
Copy class/zip/jar file into
directory “ext”
DbEdit plugins : install
Edit database directly in Eclipse dbedit_1.0.3_1.bin.dist_3.X.zip
Activate DbEdit
Connecting DbEdit with MySQL
Editing Database with DBEdit
Database data
Database structure
Attribute properties
Execute SQL command with DbEdit
JDBC Programming procedure
JDBC Driver Loading
Class.forName()
DriverManager.getConnection
Connecting to database
connection.createStatement()
Making of SQL Statement
Statement.executeQuer
Execution of SQL Statement
y/Update()
Operation of ResultSet
Resultset.getParameter
Closing of connection
Connection.close()
Loading of JDBC driver
Public static class java.lang.Class.forName(String
className) throws ClassNotFoundException
JDBC driver is described by ClassName :
mydriver.ClassName
Create an instance of this class to load JDBC driver
Loading of JDBC driver : Exemple
Exemple : Loading JDBC driver of MySQL database
Class.forName ("com.mysql.jdbc.Driver");
try {
System.err.println (“Do not connect");
} catch (ClassNotFoundException e){
Note : set CLASSPATH to find JDBC Driver class (slide 5)
}
Connection to database
Connection java.sql.DriverManager.getConnection(String urlDatabase, String userName, String password) throws SQLException
Create a connection to the urlDatabase : return the
“Connection” object
URL format
jdbc:
URL exemple:
String url = "jdbc:mysql://localhost:3306/qlsv“;
Connection to database : Exemple
String userName = “student"; String userPassword = “student"; String url = "jdbc:mysql://localhost:3306/qlsv"; try {
// Connection to database con = DriverManager.getConnection (url,userName,userPassword);
}
catch (SQLException e) { e.printStackTrace();
}
Making of SQL statement
Statement java.sql.Connection.createStatement() throws
SQLException
Return a object as Statement interface
Exemple :
Statement stmt = null; try {
stmt = con.createStatement();
} catch (SQLException e) { e.printStackTrace();
}
Execution of SQL Statement
executeQuery (String sql)
Executes the SELECT statement.
executeUpdate (String sql)
Executes the given SQL statement, which may be an
INSERT, UPDATE, or DELETE statement.
Execution of Select SQL statement
ResultSet java.sql.Statement.executeQuery(String
sqlStatement) throws SQLException
Execute Select SQL statement
Return an ResultSet object
Execution of Select SQL statement : Exemple
Statement stmt = null; ResultSet res = null; String sql = "Select * From Student"; try {
res = stmt.executeQuery(sql);
} catch (SQLException e) { e.printStackTrace();
}
Processing data in a ResultSet object
Start
rs.next
rs.getInt(“ID”)
rs.getString(“NAME”)
rs.getInt(1)
rs.getString(2)
List of getting data method
SQL Data Java data type Java method
String getString
CHAR, VARCHAR, LONGVARCHAR NUMERIC, DECIMAL java.math.Decimal getBigDecimal
BIT boolean getBoolean
TINYINT byte getByte
SMALLINT short getShort
INTEGER int getInt
BIGINT long getLong
REAL float getFloat
FLOAT, DOUBLE double getDouble
byte[] getBytes
BINARY, VARBINARY, LONGVARBINARY DATE java.sql.Date getDate
TIME java.sql.Time getTime
Execution of Select SQL statement : Exemple
String sql = "Select * From Student"; try {
res = stmt.executeQuery(sql); while (res.next()) {
Integer id = res.getInt("ID"); String name = res.getString("Name");
System.out.println(id + " " + name);
}
} catch (SQLException e) { e.printStackTrace();
}
ResultSet : exemple
Execution of others SQL statement : INSERT, UPDATE, DELETE
Syntax: int java.sql.Statement.executeUpdate(String
sqlStatement) throws SQLException
Execute SQL statement: INSERT, UPDATE, or DELETE
statement
Return: either
(1) the row count for SQL Data Manipulation Language
(DML) statements
Or (2) 0 for SQL statements that return nothing
Exemple Update SQL Statement
String sql = "Update Student Set score=8 Where id=3"; int count = 0; try {
// Execute Select SQL statement count = stmt.executeUpdate(sql); if (count == 0)
System.out.println("None record updated!");
else
System.out.println(count + " records updated!");
} catch (SQLException e) {
e.printStackTrace();
}
Exemple Update SQL Statement
Result :
Close of connection
try {
stmt.close(); con.close();
} catch (SQLException e) { e.printStackTrace();
}
Application sample : Summary
Create database “qlsv” and table “student” in
MySQL
Use DbEdit to insert student’s information into table
Student
Java Program :
Connect to database Calling a Query SQL statement Calling a Update SQL statement Close connection
Database Administation with MySQL 1
Display all databases installed in MYSQL :
Show databases;
Database Administation with MySQL 2
Create a database :
CREATE DATABASE TEMPDB;
Delete that database :
DROP DATABASE TEMPDB;
Use a database : USE TEMPDB;
Display tables in a database :
SHOW TABLES;
Create a table
CREATE TABLE table_name ( column_name1 type [modifiers]
[, column_name2 type [modifiers]] )
Create table Student : CREATE TABLE student ( ID int(6) PRIMARY KEY, NAME varchar(30), ADDRESS varchar(30), PHONE varchar(10), score int(11), } ENGINE=InnoDB DEFAULT CHARSET=utf8
Input records with DbEdit
Show all students : declaration
import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.DriverManager; import java.sql.SQLException;
public class ShowAllStudents { Connection con = null; Statement stmt = null; String userName = "root"; String userPassword = "quangnh";
String drv = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/qlsv";
Show all students : connecting to a database
try {
Class.forName (drv);
} catch (ClassNotFoundException e){
System.err.println ("Do not connect to database");
}
try {
// Connection to database con = DriverManager.getConnection(url,userName,userPassword); stmt = con.createStatement();
} catch (SQLException e) { e.printStackTrace();
}
Show all students : connecting to a database
ResultSet res = null; String sql = "Select * From Student“; try {// Execute Select SQL statement res = stmt.executeQuery(sql); while (res.next()) {
int id = res.getInt("ID"); String name = res.getString("Name"); int mark = res.getInt("mark"); String address = res.getString("Address"); System.out.println(id + " " + name + " “ + address + " " + mark);
}
} catch (SQLException e) { e.printStackTrace();
} } // end of main
Close all of object
finally { try {
catch (SQLException e) { e.printStackTrace();
// Close of result set if(res != null) {
} }
res.close();
} // Close of statement if(stmt != null) {
stmt.close();
} // Close of database if(con != null) {
con.close();
}
}
Handson exercise
Install softwares necessary :
Install MySQL Server Install DbEdit plugins to Eclipse Test Java programs with JDBC :
Test the ShowAllStudents exemple in the lecture Write a Java program to display all of student who has 9
marks.
Update all student who has 7 marks with new 8 marks. Insert into database the following student : “Nguyen Xuan Huy”, “Ha Noi”, “0983567459”, “7”
Delete all student who live in “Ha Tay”
DROP TABLE table_name Alter table student change score mark int