JDBC(Java Database
Connectivity)
Minshuo LI
Why JDBC?
API for
Oracle
Oracle
API for
C SqlServer
SqlServer
C++
Java API for
Mysql Mysql
API for
DB2 DB2
Why JDBC?
API for
Oracle Oracle
ODBC
API for
C SqlServer SqlServer
C++
Java
API for
JDBC Mysql Mysql
API for
DB2 DB2
Tow points of JDBC
Different
Uniform database
interface interface
JDBC Oracle
JDBC SqlServer
Java
JDBC Mysql
JDBC DB2
Connecting to the Database
Core interface and class of JDBC
java.sql package
Javax.sql package
The basic classes and interfaces of the JDBC
API
javax.sql package
Important interface :
javax.sql.DataSource
javax.sql.RowSet
JDBC programming steps
1.Load the Driver
Class.forName()|Class.forName().new Instance()|new DriverName()
instance driver and automatically register to DriverManager
call DriverManager.registerDriver()
2. Connect to the Database
DriverManager.getConnection(url,username,password)
3. Execute the SQL
Connection.createStatement()
Statement.executeQuery()
Statement.executeUpdate()
4. Retrieve the result date
while(rs.next())
5. Show the result data
change database type to Java type (getxxx) 6. Close
Close the resultset | close the Statement | close the Connection
JDBC API core structure
MySQL JDBC
driver
Download
1.Mysql
http://dev.mysql.com/downloads/mysql/
mysql-installer-community-5.7.12.0.msi
mysql-installer-web-community-5.7.12.0.msi
2.Mysql driver(Standardized database driver for
Java platforms and development)
Site:http://dev.mysql.com/downloads/connector/
j/
mysql-connector-java-5.1.39.zip
MySQL database installation
MySQL database
installation(1)
click
13
MySQL database
installation(2)
click
choose
14
MySQL database
installation(3)
choose
click
15
MySQL database
installation(4)
choose
click
16
MySQL database
installation(5)
click
17
MySQL database
installation(6)
click
18
MySQL database
installation(7)
click
19
MySQL database
installation(8)
click
20
MySQL database installation(9)
choose
MySQL database installation(10)
“1234”
MySQL database
installation(11)
click
23
MySQL database installation(12)
Create database
MySQL driver installation
Copy mysql-connector-java-5.1.18-bin.jar to:
1.server‟s lib directory.
2.project‟s lib directory.
key work step(1)
1.Load and register database driver.
Class.forName(DRIVER)
if driver is loaded successfully, the instance
of Driver will register in class DriverManager.
Example:
Class.forName("com.mysql.jdbc.Driver");
key work step(2)
2.Create the jdbc connection.
DriverManager.getConnection(URL,USER,PASSWOR
D)
Class DriverManager support the basic service for
managing a set of JDBC drivers.
Example:
string url=“jdbc:mysql://localhost:3306/user”;
string user=“root”;
string pass=“root”;
Connection
con=DriverManager.getConnection(url,user,pass);
Add:URL
Generic format of url:
<protocol>:<subprotocol>:<subname>
In JDBC, protocol is defined as jdbc,
<subprotocol> is the Driver name,such as
mysql,<subname>is composed of three
part:
//<host>[:<port>][/<databaseName>]
Drivers and URLs of different databases
database driver url
SQLServer com.microsoft.sqlserver.jdbc.S jdbc:sqlserver://localhost:1433;
QLServerDriver DatabaseName=dbName
Oracle oracle.jdbc.driver.Oracle jdbc:oracle:thin:@IP:Port:SID
Driver
MySQL com.mysql.jdbc.Driver jdbc:mysql://IP:Port/dbName
Access sun.jdbc.odbc.JdbcOdbcDriver jdbc:odbc:driver={Microsoft Access
Driver(*.mdb)};DBQ=dbFileName
key work step(3)
3.Create statement
Statement st = conn.CreateStatement();
PreparedStatement ps = conn.prepareStatement(sql);
CallableStatement cs=conn.prepareCall(sql)
Three kinds of statement:
① Statement(simple SQL statement without parameter)
② PreparedStatement (precompiled SQL statement with parameters)
An object that represents a precompiled SQL statement.
③ CallableStatement(stored procedure)
The interface used to execute SQL stored procedures.
http://docs.oracle.com/javase/7/docs/api/
Statement
Subinterfaces:CallableStatement, PreparedStatement
The object used for executing a static SQL statement and returning the
results it produces.
Methods:
① boolean execute(String sql) throws SQLException
//Executes the given SQL statement, which may return multiple results.
② ResultSet executeQuery(String sql) throws SQLException
//Executes the given SQL statement, which returns a single ResultSet
object. SELECT staement
③ int executeUpdate(String sql) throws SQLException
//Executes the given SQL statement, which may be an INSERT, UPDATE,
or DELETE statement or an SQL statement that returns nothing, such as
an SQL DDL statement.
PreparedStatement
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
Note: The setter methods (setShort, setString, and so on) for setting
IN parameter values must specify types that are compatible with the
defined SQL type of the input parameter. For instance, if the IN
parameter has SQL type INTEGER, then the method setInt should be
used.
If arbitrary parameter type conversions are required, the method
setObject should be used with a target SQL type.
Exmaple:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
key work step(4)
4.Execute statement
Example:
String sql = "INSERT INTO user_list ( user_name,
user_password ) VALUES ( 'Eric', '123' )";
stmt = conn.createStatement();
stmt.executeUpdate(sql);
sql = “DELETE FROM jdbc_teaching.user_list WHERE
user_name = „Eric‟”;
stmt = conn.createStatement();
stmt.executeUpdate(sql);
String sql = "SELECT * FROM user_list WHERE
user_name = '?'";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString( 1, "Eric" );
ResultSet rs = stmt.executeQuery(sql);
key work step(5)
5.Process result set.
ResultSet rs = stmt.executeQuery("SELECT a, b FROM
TABLE2");
Interface ResultSet:
A table of data representing a database result set, which is
usually generated by executing a statement that queries the
database.
A ResultSet object maintains a cursor pointing to its current
row of data. Initially the cursor is positioned before the first
row. The next method moves the cursor to the next row, and
because it returns false when there are no more rows in the
ResultSet object, it can be used in a while loop to iterate
through the result set.
Example:
while (rs.next()==true){
userName = rs.getString( "user_name" ); String
userPassword = rs.getString( 2 );
System.out.println( userName + " : " +
userPassword ); }
key work step(6)
Close result set
Close statement
Close connection
Example:
rs.close();
stmt.close();
conn.close();
task
Realize CRUD:insert,select,update,delete.