Sunteți pe pagina 1din 38

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


manage two or more JDBC drivers DriverManager class in the java.sql package

JDBC Driver Manager


JDBC

JDBC Driver API

defined for connecting between the JDBC driver manager and JDBC drivers access each database 4 types :

JDBC Driver

JDBC-ODBC bridge Native API partly Java technology-based driver Net-protocol all - Java technology-based driver Native-protocol Java technology-based driver

Setting classpath for JDBC

Driver class as a archive file:

classpath=% classpath %;C:\mysql\ mysqlconnector-java-5.1.7bin.jar; classpath=% classpath %;C:\mysql\classes;

Driver class as a directory:

Copy class/zip/jar file into directory ext

DbEdit plug-ins : 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 Connecting to database

Class.forName() DriverManager.getConnection

Making of SQL Statement

connection.createStatement()
Statement.executeQuery /Update() Resultset.getParameter Connection.close()

Execution of SQL Statement


Operation of ResultSet

Closing of connection

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


try {
Class.forName ("com.mysql.jdbc.Driver");

} catch (ClassNotFoundException e){


System.err.println (Do not connect");

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:<subprotocol>://hostname:port/databaseName 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.getInt(1)

rs.getString(NAME) rs.getString(2)

List of getting data method


SQL Data Java data type Java method

CHAR, VARCHAR, LONGVARCHAR


NUMERIC, DECIMAL BIT TINYINT SMALLINT INTEGER BIGINT

String
java.math.Decimal boolean byte short int long

getString
getBigDecimal getBoolean getByte getShort getInt getLong

REAL
FLOAT, DOUBLE BINARY, VARBINARY, LONGVARBINARY DATE TIME

float
double byte[] java.sql.Date java.sql.Time

getFloat
getDouble getBytes getDate 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 students 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 import import import import java.sql.Connection; java.sql.Statement; java.sql.ResultSet; java.sql.DriverManager; 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 { // 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(); } } catch (SQLException e) { e.printStackTrace(); } }

Hands-on exercise

Install softwares necessary :


Install MySQL Server Install DbEdit plug-ins to Eclipse


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 :

Test Java programs with JDBC :


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