Internet programiranje Java i rad sa podacima

© SI1P1 – 2004

1/15

Java i baze podataka
podsistem za komunikaciju sa RDBMS serverima zasnovanim na SQL-u celokupan podsistem je definisan u standardnom paketu ODBC i JDBC
• Open Database Connectivity (ODBC) je standardni API za povezivanje sa RDBMS

java.sql

JDBC je JAVA API za baze podataka bazirane na SQL jeziku. DBC je predstavljen u obliku na nivou poziva SQL interface za Javu. Pomoću klasa iz ovog paketa se mogu izvršavati SQL naredbe i manipulisati sa rezultatima dobijenim na osnovu ovih naredbi. JDBC API sadrži niz abstraktnih Java interface koji dozvoljavaju programeru da ostvari konekciju sa određenom bazom podataka, izvrši SQL naredbe i obradi dobijene rezultate.

© SI1P1 – 2004

2/15

Realizacija

Driver Manager

Connection

Connection

Connection

Statement

Statement

Statement

Statement

Resultset

Resultset

Resultset

© SI1P1 – 2004

3/15

JDBC drajveri
skup klasa koje implementiraju interfejse iz paketa
java.sql

obezbjeđuje ih svaki proizvođač RDBMS servera za svoje sisteme svi drajveri se na isti način koriste instalacija drajvera = uključivanje u CLASSPATH isti Java kod se može koristiti za rad sa serverima različitih proizvođača, uz korišćenje odgovarajućeg JDBC drajvera

© SI1P1 – 2004

4/15

JDBC i klijent/server model
pristup bazi podataka iz Java aplikacije dvoslojni (two-tier) model troslojni (three-tier) model CGI skriptovi i servleti Web servisi

© SI1P1 – 2004

5/15

Pristup bazi podataka iz Java aplikacije
Java JDBC aplikacija TCP/IP mreža RDBMS

Java aplet

WWW server JDBC TCP/IP mreža WWW server RDBMS

Java aplet
© SI1P1 – 2004

Java server

RDBMS
JDBC
6/15

Složeniji troslojni model

RDBMS WWW server Java server
JDBC

Java aplet

RDBMS ... RDBMS

© SI1P1 – 2004

7/15

CGI skriptovi

RDBMS WWW čitač WWW server CGI
JDBC

RDBMS ... RDBMS

© SI1P1 – 2004

8/15

Servleti

RDBMS WWW čitač WWW server servlet
JDBC

RDBMS ... RDBMS

© SI1P1 – 2004

9/15

Osnovne klase
java.sql.DriverManager sprovodi učitavanje driver-a baze podataka i omogućava podršku za kreiranje nove konekcije java.sql.Connection predstavlja konekciju sa određenom bazom podataka java.sql.Statement izvršava se u obliku container-a za izvršavanje SQL naredbi u okviru uspostavljene konekcije java.sql.ResultSet kontroliše pristup rezultatima dobijenim izvršavanjem određene SQL naredbe java.sql.Statement interface ima dva važna podtipa:
• java.sql.PreparedStatement za izvršavanje pre-kompajlirane SQL naredbe • java.sql.CallableStatement za izvršavanje poziva stored procedura koje 10/15 © SI1P1 – 2004 postoje u okviru baze podataka.

Inicijalizacija
JDBC URL ima sledeću strukturu: jdbc:<subprotocol>:<subname> subprotocol je ime određene vrste mehanizma pristupa bazi podataka koji može biti podržan od jednog ili više drajvera. Sadržaj i sintaksa dela subname zavisi od subprotocola. JDBC management nivo mora da zna koji drajver je raspoloživ i koji drajver se koristi. Primer inicijalizacije drajvera baze podataka: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("org.gjt.mm.mysql.Driver”);

© SI1P1 – 2004

11/15

Elementi JDBC drajvera
Connection Statement PreparedStatement CallableStatement ResultSet ResultSetMetaData

© SI1P1 – 2004

12/15

Primer

STUDENT STUDENT_ID IME PREZIME INTEGER VARCHAR(25) VARCHAR(25)

© SI1P1 – 2004

13/15

Uspostavljanje veze
Učitavanje JDBC drajvera
Class.forName(“com.mysql.jdbc.Driver"); Class.forName(“com.informix.jdbc.IfxDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Uspostavljanje veze Connection conn = DriverManager.getConnection( "jdbc:mysql://student.etfbl.net:3306/STUDENT", “USERNAME", “PASSWORD"); Connection conn = DriverManager.getConnection( "jdbc:informix-sqli://student.etfbl.net:1526/STUDENT:INFORMIXSERVER=ds_server", “USERNAME", “PASSWORD"); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@student.etfbl.net:1526:STUDENT", “USERNAME", “PASSWORD"); Connection conn = DriverManager.getConnection( "jdbc:odbc:student", “USERNAME", “PASSWORD");

© SI1P1 – 2004

14/15

Izuzeci
Učitavanje JDBC drajvera Class.forName(“com.mysql.jdbc.Driver"); - ClassNotFoundException

Uspostavljanje veze Connection conn = DriverManager.getConnection( "jdbc:mysql://student.etfbl.net:3306/STUDENT", “USERNAME", “PASSWORD"); - SQLException Ostale metode – SQLException try-catch blok Završetak komunikacije s bazom podataka - metoda close() klase Connection

© SI1P1 – 2004

15/15

Postavljanje upita
Statement i ResultSet
String query = "SELECT ime, prezime FROM studenti"; Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(query); while (rset.next()) { System.out.println( rset.getString(1) + " " + rset.getString(2)); } rset.close(); stmt.close();

© SI1P1 – 2004

16/15

DML naredbe

INSERT, UPDATE, DELETE
String query = “INSERT INTO studenti (ime, prezime) VALUES (‘Nenad’, ‘Nenadovic’) "; Statement stmt = conn.createStatement(); int n = stmt.executeUpdate(query); stmt.close();

© SI1P1 – 2004

17/15

Izvršavanje istih SQL naredbi više puta uzastopno
PreparedStatement
PreparedStatement stmt = conn.prepareStatement( "INSERT INTO studenti (id, ime, prezime) values (?, ?, ?)"); stmt.setInt(1, 1); stmt.setString(2, new String(“Marko")); stmt.setString(3, new String(“Markovic")); stmt.executeUpdate(); stmt.setInt(1, 2); stmt.setString(2, new String(“Nenad")); stmt.setString(3, new String(“Nenadovic")); stmt.executeUpdate(); stmt.close(); U slučaju SELECT naredbe poziva se stmt.executeQuery();
© SI1P1 – 2004 18/15

Pozivanje uskladištenih procedura i funkcija

Procedure koje se smještaju u okviru baze podataka Dostupne za pozivanje od strane klijenta Proširenja SQL-a (PL/SQL, Transact-SQL,...)

© SI1P1 – 2004

19/15

Pozivanje uskladištenih procedura i funkcija
CallableStatement
// pozivamo funkciju uradi CallableStatement stmt = conn.prepareCall( "{? = call uradi (?, ?)}");
za funkcije

// postavljamo parametre stmt.setString(2, new String("Sima")); stmt.setString(3, new String("Simic")); stmt.registerOutParameter(1, Types.INTEGER); stmt.executeQuery(); // citamo rezultat funkcije System.out.println("Status: " + stmt.getInt(1));

© SI1P1 – 2004

20/15

Primer 2
import java.sql.*; public class JDBCDemoCreateTable { public static void main(String[] args) { // 1. step loading the driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 2. step making the connection String url = "jdbc:odbc:Primer2" ; String myLogin = "mika" ; // the name you use to log in to the DBMS String myPassword = "mika" ; // your password for the DBMS try { Connection con = DriverManager.getConnection( url, myLogin, myPassword ); String createTableCoffees = "CREATE TABLE COFFEES " + "(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)"; // 3. step creating JDBC sStatement. Statement stmt = con.createStatement(); stmt.executeUpdate(createTableCoffees); } catch ( SQLException e ) { System.err.println( e ); } }catch ( ClassNotFoundException e) { System.out.println("Error : " + e ); } 21/15 © SI1P1 – 2004 } } //

Primer 2
import java.sql.*; public class JDBCDemoUpdateTable { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { Connection con = DriverManager.getConnection( "jdbc:odbc:Primer2", "mika", "mika" ); Statement stmt = con.createStatement(); String updateTableCoffees = "INSERT INTO COFFEES VALUES ('Col', 101, 7, 0, 0)" ; stmt.executeUpdate( updateTableCoffees ); updateTableCoffees = "INSERT INTO COFFEES VALUES ('French_Roast', 49, 8.99, 0, 0)" ; stmt.executeUpdate( updateTableCoffees ); updateTableCoffees = "INSERT INTO COFFEES VALUES ('Espresso', 150, 9.99, 0, 0)" ; stmt.executeUpdate( updateTableCoffees ); updateTableCoffees = "INSERT INTO COFFEES VALUES ('Colombian_Dec', 101, 9.1, 0, 0)" ; stmt.executeUpdate( updateTableCoffees ); updateTableCoffees = "INSERT INTO COFFEES VALUES ('French', 49, 9.99, 0, 0)" ; stmt.executeUpdate( updateTableCoffees ); 22/15 © SI1P1 – 2004 } catch ( SQLException e ) { System.err.println( e ); } }catch ( ClassNotFoundException e) { System.out.println("Error : " + e ); } }}

import java.sql.*; public class JDBCDemoSelectTable { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { Connection con = DriverManager.getConnection( "jdbc:odbc:Primer2", "mika", "mika" ); Statement stmt = con.createStatement(); String queryTableCoffees = "SELECT COF_NAME, SUP_ID, PRICE, SALES, TOTAL FROM COFFEES" ; ResultSet rs = stmt.executeQuery( queryTableCoffees ); while (rs.next()) { String coffeName = rs.getString("COF_NAME"); int supplierId = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt( 4 ); int total = rs.getInt( 5 ); System.out.println( coffeName + " " + supplierId + " " + price + " " +sales + " " + total ); } } catch ( SQLException e ) { System.err.println( e ); } } catch ( ClassNotFoundException e) { System.out.println("Error : " 23/15 © SI1P1 – 2004 + e ); } }}

import java.sql.*; public class JDBCDemoPreparedStatement { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { Connection con = DriverManager.getConnection( "jdbc:odbc:BootCamp", "mika", "mika" ); PreparedStatement updateSalesPrepared = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = {"Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf"}; int len = coffees.length; for(int i = 0; i < len; i++) { updateSalesPrepared.setInt(1, salesForWeek[i]); // setting up first parameter updateSalesPrepared.setString(2, coffees[i]); // setting up second parameter updateSalesPrepared.executeUpdate(); // executing update © SI1P1 – 2004 }

24/15

Statement stmt = con.createStatement(); String queryTableCoffees = "SELECT COF_NAME, SALES FROM COFFEES" ; ResultSet rs = stmt.executeQuery( queryTableCoffees ); while (rs.next()) { String coffeName = rs.getString("COF_NAME"); int sales = rs.getInt(2); System.out.println( coffeName + " " + sales ); } } catch ( SQLException e ) { System.err.println( e ); } } catch ( ClassNotFoundException e) { System.out.println("Error : " + e ); } }

}

© SI1P1 – 2004

25/15

import java.sql.*; public class JDBCDemoCallableStatement { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:BootCamp" ; String myLogin = "mika" ; // the name you use to log in to the DBMS String myPassword = "mika" ; // your password for the DBMS try { Connection con = DriverManager.getConnection( url, myLogin, myPassword ); // A stored procedure is a group of SQL statements that form a logical unit and perform a particular task String createProcedure = "create procedure SHOW_SUPPLIERS " + "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME";
© SI1P1 – 2004 26/15

Statement stmt = con.createStatement(); stmt.executeUpdate(createProcedure); // Calling a Stored Procedure from JDBC CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); while (rs.next()) { String supName = rs.getString("SUP_NAME"); String coffyName = rs.getString("COF_NAME"); System.out.println( supName + " " + coffyName ); } }catch ( SQLException e ) { System.err.println( e ); } } catch ( ClassNotFoundException e) { System.out.println("Error : " + e ); } }

}

© SI1P1 – 2004

27/15

Dijagram izvršavanja

© SI1P1 – 2004

28/15

SQL type

TINY INT

SMA LLIN T

INTE GER

BIGI NT

REA L

FLO AT

DOU BLE

DECI MAL

NUM ERIC

BIT

CHA R

VAR CHA R

LON GVA RCH AR

BINA RY

VAR BINA RY

LON GVA RBIN ARY

DAT E

TIME

TIME STA MP

Java Type getBy te

String

String

String

java. math. BigD ecima l

java. math. BigD ecima l

boole an

byte

short

int

long

float

doubl e

doubl e

byte[]

byte[]

byte[]

java.s ql.Dat e

java.s ql.Ti me

java.s ql.Ti mesta mp

X

x

x

x

x

x

x

x

x

x

x

x

x

getSh ort

x

X

x

x

x

x

x

x

x

x

x

x

x

getInt getLo ng

x

x

X

x

x

x

x

x

x

x

x

x

x

x

x

x

X

x

x

x

x

x

x

x

x

x

getFl oat

x

x

x

x

X

x

x

x

x

x

x

x

x

getDo uble

x

x

x

x

x

X

X

x

x

x

x

x

x

© SI1P1 – 2004
x x x x x x x X X x x x x

getBi gDeci mal

29/15

SQL type

TINY INT

SMA LLIN T

INTE GER

BIGI NT

REA L

FLO AT

DOU BLE

DECI MAL

NUM ERIC

BIT

CHA R

VAR CHA R

LON GVA RCH AR

BINA RY

VAR BINA RY

LON GVA RBIN ARY

DAT E

TIME

TIME STA MP

Java Type getBo olean getStr ing getBy tes getDa te getTi me getTi mesta mp getAs ciiStr eam getUn icode Strea m

String

String

String

java. math. BigD ecima l

java. math. BigD ecima l

boole an

byte

short

int

long

float

doubl e

doubl e

byte[]

byte[]

byte[]

java.s ql.Dat e

java.s ql.Ti me

java.s ql.Ti mesta mp

x

x

x

x

x

x

x

x

x

X

x

x

x

x

x

x

x

x

x

x

x

x

x

X

X

x

x

x

x

x

x

x

X x x x x x x

X

x X X x x

x

x

x

x

x

X

x

x

X

x

x

x

x

x

X

x

x

x

getBi naryS tream

x

x

X

© SI1P1 – 2004
getOb ject x x x x x x x x x x x x x x x x x x

30/15
x

Upravljanje transakcijama

conn.commit(); conn.rollback(); conn.setAutoCommit(false);

© SI1P1 – 2004

31/15

Klasa Vector
java.lang.Object | +--java.util.AbstractCollection | +--java.util.AbstractList | +--java.util.Vector Vector v = new Vector(); Vector v = new Vector(25); v.addElement("carrots"); v.addElement("broccoli"); v.addElement("cauliflower"); String s = (String)v.lastElement(); String s1 = (String)v.elementAt(0); String s2 = (String)v.elementAt(2); v.insertElementAt("squash", 1); v.insertElementAt("corn", 0); v.removeElementAt(3); © SI1P1 – 2004

32/15

Klasa Vector
v.setElementAt("peas", 1); v.removeAllElements(); boolean isThere = v.contains("celery"); int i = v.indexOf("squash"); v.removeElement("cauliflower"); int size = v.size(); v.setSize(10);

© SI1P1 – 2004

33/15

Klasa Vector
import java.util.* ; class VectorDemo { public static void main(String[] args) { Vector a = new Vector(); a.addElement( new Boolean(true)); a.addElement( new Integer(5)); a.addElement( "some string" ); a.addElement( new Double(5.2)); a.addElement( new Date()); System.out.println( "a.toString()= " + a.toString() ); System.out.println( "a.size()= " + a.size() ); for ( int i = 0 ; i < a.size() ; i++ ){ System.out.print( "a.get( " + i + " ) =" + a.get(i) + " System.out.println( "a.elementAt( " + i + " ) = " + a.elementAt(i) ); } } }

" );

© SI1P1 – 2004

34/15

Klasa Vector
import java.util.* ; class VectorDemo1 { public static void main(String[] args) { Vector matrix = new Vector(); for ( int i = 0 ; i < 5 ; i++ ){ Vector row = new Vector(); for ( int j = 0 ; j < 6 ; j++ ){ row.addElement((new Integer(i)).toString()+(new Integer(j)).toString() ); } matrix.addElement(row); } for ( int i = 0 ; i < 5 ; i++ ){ System.out.println(); for ( int j = 0 ; j < 6 ; j++ ){ System.out.print( ((Vector)matrix.elementAt(i)).elementAt(j) + " " ); } } } 35/15 © SI1P1 – 2004 }

Sign up to vote on this title
UsefulNot useful