Antony - Java Database Programming JDBC Connections
Antony - Java Database Programming JDBC Connections
Ngorora
JDBC 1
Agenda
JDBC
load driver
Connect to a database
Create statements
Execute statements
Process results
Explore database metadata
JDBC 2
JDBC
JDBC 4
JDBC Drivers
JDBC 5
RELATIONSHIPS
JDBC 6
Drivers
Database Driver class Source
JDBC 7
Steps to access database
Load drivers
Establish connections
Creating statements
Executing statements
Processing ResultSet
Close connection
JDBC 8
1 - Load drivers
Statement:
Class.forName(“……”);
Driver is concrete class that implements the
java.sql.Driver interface
List all drivers for all databases you want to
access
JDBC 9
2 - Connection
JDBC 10
Connection - cable
Program
Databases
JDBC 11
JDBC URLs
Access jdbc:odbc:dataSource
MySQL jdbc:msql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
JDBC 12
Example: Access database
Connection connection =
DriverManager.getConnection(“jdbc:odbc:
ExampleMDBDataSource”);
JDBC 13
Example: MySQL database
Connection connection =
DriverManager.getConnection
(“jdbc:mysql://localhost/javabook”, “scott”,
“tiger”);
Connection connection =
DriverManager.getConnection
(“jdbc:oracle:thin:@liang.armstrong.edu:1521:
orcl”, “scott”, “tiger”);
Database on liang.armstrong.edu
JDBC 15
3 – Creating statements
Statement statement =
connection.createStatement();
JDBC 16
Statements - cart
Program
SQL
statements
Results
Databases
JDBC 17
4 – Executing statements
Three options:
JDBC 18
Update command
statement.executeUpdate(“create
Table Temp (col1 char(5), col2 char(5))”);
JDBC 19
Query command
ResultSet resultSet =
statement.executeQuery(“select firstName,
mi, lastName from Student where lastName
+ ‘ = Smith’”);
JDBC 20
5 – Processing ResultSet
JDBC 21
Example
while(resultSet.next())
S.o.p(resultSet.getString(1) + “ ” +
resultSet.getString(2) + “ ”
resultSet.getString(3);
JDBC 22
6 – Close connection
connection.close();
JDBC 23
The end…..
JDBC 24