Vous êtes sur la page 1sur 15

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 java.sql.*; 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 Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection
("jdbc:postgresql://localhost:5432/csc343h-user", "user", "pass");
execute(SQL) Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("select name, number
Result handling from mytable where number < 2");
while( rs.next() )
yes System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")");
More
results ?
rs.close();
no stmt.close()
close ResultSet con.close();
} catch(Exception e){ “catch” an Exception here
(could be an SQLException)
close Statment System.err.println(e); }
} } 4
close Connection
What do I need to run this code?

 Download the driver


http://jdbc.postgresql.org/download.html

 Compile the code


javac JDBCExample.java

 Run your code (with CLASSPATH option)


java -cp /path-to-jdbc-dir/postgresql-9.1-903.jdbc4.jar:. JDBCExample

JDBCExample.java
import java.sql.*;

public class jdbctest {


public static void main(String args[]){
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection
("jdbc:postgresql://localhost:5432/csc343h-user", "user", "pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("select name, number from pcmtable where number < 2");
while( rs.next() )
System.out.println(rs.getString(1) + " (" + rs.getInt(2) + ")");
rs.close();
stmt.close()
con.close();
} catch(Exception e){
System.err.println(e); } 5
} }
JDBCExample.java: General Instructions

6
JDBCExample.java: Import SQL Package, Prepare DB Objects

7
JDBCExample.java: Load the driver!

Notice that in A2 you need to have


this line in your constructor
method: Assignment2()

8
JDBCExample.java: Make the connection to the DB..

9
JDBCExample.java: Create + Execute a Statement!

10
JDBCExample.java: INSERTs, UPDATEs..

11
JDBCExample.java: Use Prepared Statement for Insertion!

12
JDBCExample.java: Get and Process a Result Set..

13
JDBCExample.java: DROP a table and close connection..

14
Demo..

Vous aimerez peut-être aussi