CS343 Embedded SQL
Tutorial
JDBC Architecture
JDBC - Simple Example
loadDriver Steps:
1- Load the driver and register it with the driver manager
getConnection (provided you’ve already downloaded the driver “jar”
file)
createStatement 2- Connect to a database
3- Create a statement
execute(SQL)
4- Execute a query and retrieve the results, or make
changes to the database
Result handling
5- Disconnect from the database
yes
More
results ?
no
close ResultSet
close Statment
3
close Connection
JDBC - Simple Example
loadDriver import [Link].*; API for accessing and processing DB data
public class jdbctest {
Java launcher looks
getConnection public static void main(String args[]){
for “main” method
try{
createStatement [Link]("[Link]");
Connection con = [Link]
("jdbc:postgresql://localhost:5432/csc343h-user", "user", "pass");
execute(SQL) Statement stmt = [Link]();
ResultSet rs = [Link] ("select name, number
Result handling from mytable where number < 2");
while( [Link]() )
yes [Link]([Link](1) + " (" + [Link](2) + ")");
More
results ?
[Link]();
no [Link]()
close ResultSet [Link]();
} catch(Exception e){ “catch” an Exception here
(could be an SQLException)
close Statment [Link](e); }
} } 4
close Connection
What do I need to run this code?
Download the driver
[Link]
Compile the code
javac [Link]
Run your code (with CLASSPATH option)
java -cp /path-to-jdbc-dir/[Link]:. JDBCExample
[Link]
import [Link].*;
public class jdbctest {
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con = [Link]
("jdbc:postgresql://localhost:5432/csc343h-user", "user", "pass");
Statement stmt = [Link]();
ResultSet rs = [Link]
("select name, number from pcmtable where number < 2");
while( [Link]() )
[Link]([Link](1) + " (" + [Link](2) + ")");
[Link]();
[Link]()
[Link]();
} catch(Exception e){
[Link](e); } 5
} }
[Link]: General Instructions
6
[Link]: Import SQL Package, Prepare DB Objects
7
[Link]: Load the driver!
Notice that in A2 you need to have
this line in your constructor
method: Assignment2()
8
[Link]: Make the connection to the DB..
9
[Link]: Create + Execute a Statement!
10
[Link]: INSERTs, UPDATEs..
11
[Link]: Use Prepared Statement for Insertion!
12
[Link]: Get and Process a Result Set..
13
[Link]: DROP a table and close connection..
14
Demo..