Database programming in Java
description
Transcript of Database programming in Java
![Page 1: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/1.jpg)
Database programming in Java
An introduction to Java Database Connectivity (JDBC)
![Page 2: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/2.jpg)
Introduction
Two standard ways to work with databases in Java JDBC
A Call level interface similar to ODBC SQLJ
SQL code imbedded in Java, like SQL embedded in C
JDBC is the most common way and it’s supported by almost all database vendors
![Page 3: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/3.jpg)
Java Database Connectivity
JDBC is a specification from Sun and part of Java 2
We will talk about JDBC 2 JDBC applications are portable
Switch database without rewriting your program If there is a driver for the database If you use only standard SQL (i.e. no vendor specific
code)
JDBC is the Java version of ODBC There are four levels for JDBC drivers
![Page 4: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/4.jpg)
Level 1 Drivers
Level 1 is a JDBC-ODBC bridge The actual database communication is done
via a ODBC driver Requires the Database client library to be
installed The ODBC drivers and all libraries that the driver
needs Suns JDBC-ODBC bridge is single threaded
![Page 5: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/5.jpg)
Level 2 Drivers
This is a partly Java solution All JDBC calls are converted from to calls in
the vendor specific client API The library must be installed on the client machine
![Page 6: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/6.jpg)
Level 3 Drivers
Level 3 is a multi tier solution On the client it’s all Java
No vendor specific client library is needed The connection is made to a server that
connects to the database The server can use ODBC or some other
technology Several databases can be supported by the
server
![Page 7: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/7.jpg)
Level 4 Drivers
Level 4 is an all Java solution No client API is needed besides the JDBC
Driver This is the most common type, and the one
that we will use All JDBC calls are directly transformed to the
vendor specific protocoll Direct calls from the client to the database
server
![Page 8: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/8.jpg)
Important JDBC Classes/Interfaces java.sql.DriverManager java.sql.Driver java.sql.Connection java.sql.Statement java.sql.PreparedStatement java.sql.CallableStatement java.sql.ResultSet
Scrollable or not Updateable or not
javax.sql.DataSource
![Page 9: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/9.jpg)
java.sql.DriverManager
The DriverManager is responsible for loading the correct Driver
The DriverManager is used to get a connection to the database
![Page 10: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/10.jpg)
java.sql.Driver
This is the actual implementation of the JDBC Driver
The only part that’s vendor specific Used if DriverManager is used to get
connection Loaded with Class.forName(“driverclass”)
The driver name for Mimer SQL is “com.mimer.jdbc.Driver”
![Page 11: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/11.jpg)
java.sql.Connection
A Connection represent an actual connection to the database
The Connection is used to create statements (queries)
A Connection is returned from the DriverManager DriverManger.getConnection(url, username,
password) DriverManager.getConnection(url)
![Page 12: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/12.jpg)
java.sql.Connection – important methods setAutoCommit(boolean) createStatement() prepareStatement(“SQL query”) commit() rollback() close()
ALLWAYS close your connections
![Page 13: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/13.jpg)
java.sql.Connection – important methods getMetaData() returns a DatabaseMetaData
object From the DatabaseMetaData you can get
information about the database Vendor name Version Supported functions
![Page 14: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/14.jpg)
java.sql.Statement
A Statement is the simplest of the statement types
It’s used to pass a query to the database and to return a ResultSet
![Page 15: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/15.jpg)
java.sql.Statement - important methods executeQuery(“sql query”)
Returns a ResultSet execute(“sql query”)
Mostly used when the type of query is unknown executeUpdate(“sql query”) getResultSet() close()
ALLWAYS close your Statements
![Page 16: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/16.jpg)
java.sql.PreparedStatement
A prepared statement is a Statement with parameters
The prefered way if you have conditions in your query
Will be compiled once at the server and then cached
Give you an easier to read code
![Page 17: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/17.jpg)
java.sql.PreparedStatement – important methods Can do all that a Statement can setXXX() is used to set the different
parameters
pstmt = con.prepareStatement(“select * from person where cars=`?”);
pstmt.setInt(1,carId);
pstmt.executeQuery();
![Page 18: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/18.jpg)
java.sql.CallableStatement
CallableStatement is used to prepare and call stored procedures in the database
prepareCall(“statement”) execute()
![Page 19: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/19.jpg)
java.sql.ResultSet
The ResultSet is used to get the information from the Database
Retured from executeQuery() or getResultSet()
Like a cursor in embedded SQL Just like with Connections and Statements,
ALLWAYS close when you’re done
![Page 20: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/20.jpg)
java.sql.ResultSet
Before the first fetch, the position is before the first row
ResultSet can be of several types Updateable
Can be used to perform updates in the database directly Rows can be inserted
Scrollable The cursor can be moved forward and backwards
![Page 21: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/21.jpg)
java.sql.ResultSet – important methods next()
Used when looping over the result Returns true if there was a row to fetch and false otherwise Moves the cursor one step forward The classic loop is while(rs.next()) where rs is a ResultSet
getXXX(position) Gets the column with postion
getXXX(name) Gets the column with the matching name The name is the same as in the select list
![Page 22: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/22.jpg)
java.sql.ResultSet – important methods getMetaData() returns a ResultSetMeta
where you can get information about the ResultSet Number of columns Type of ResultSet NOT the number of rows
![Page 23: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/23.jpg)
javax.sql.DataSource
DataSource can be used instead of DriverManager and Driver If possible, use it
Retrieved via JNDI (Java Naming and Directory Interface)
DataSource ds = (DataSource)context.lookup(“java:com/env/jdbc/multi1”);
ds.getConnection();
![Page 24: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/24.jpg)
Simple example
1. package com.mimer.kurs.uu.jdbc;2. import java.sql.*;3. public class JdbcOne {4. public static void main(String[] args) {5. try{6. Class.forName("com.mimer.jdbc.Driver");7. Connection con =
DriverManager.getConnection("jdbc:mimer:multi1","fredrik","fredrik");8. Statement stmt = con.createStatement();9. ResultSet rs = stmt.executeQuery("SELECT TABLE_NAME FROM
INFORMATION_SCHEMA.TABLES");10. while(rs.next()){11. System.out.println(rs.getString("TABLE_NAME"));12. }13. }14. catch(Exception e){15. System.out.println("Error:" + e.getMessage());16. }17. }18. }
![Page 25: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/25.jpg)
More advanced example
1. package com.mimer.kurs.uu.jdbc;2. import java.sql.*;3. import java.io.*;4. public class JdbcTwo {5. public static void main(String[] args) {6. String driver="com.mimer.jdbc.Driver";7. String url="jdbc:mimer:multi1";8. String username="fredrik";9. String password="fredrik";10. ResultSet rs = null;11. PreparedStatement pstmt = null;12. Connection con = null;13. //All accessible tables for the current ident14. String query="SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE=?";15. try{16. Class.forName("com.mimer.jdbc.Driver");17. con = DriverManager.getConnection(url,username,password);18. pstmt = con.prepareStatement(query);19. pstmt.setString(1, "BASE TABLE");20. rs = pstmt.executeQuery();21. while(rs.next()){22. System.out.println(rs.getString("TABLE_NAME"));23. 24. }25. }
![Page 26: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/26.jpg)
More advanced example, continued26. catch(ClassNotFoundException cnfe){27. System.out.println("Could not load Driver");28. }29. catch(SQLException sqle){30. System.out.println("SQL Error: " + sqle.getMessage());31. }32. catch(Exception e){33. System.out.println("Error:" + e.getMessage());34. }35. finally{36. try{37. rs.close();38. }39. catch(Exception e){40. }41. try{42. pstmt.close();43. }44. catch(Exception e){45. }46. try{47. con.close();48. }49. catch(Exception e){50. }51. }52. 53. }54. }
![Page 27: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/27.jpg)
Assignment
1. Create a table in the database:create table PERSON(
PNR INTEGER,
NAME CHARACTER(10default 'Unknown',
SURNAME CHARACTER(10),
SEX CHARACTER(4) not null,
AGE INTEGER,
primary key(PNR));
![Page 28: Database programming in Java](https://reader035.fdocuments.in/reader035/viewer/2022062222/56815265550346895dc09880/html5/thumbnails/28.jpg)
Assignment
Create a simple Java program that adds persons to the database. It can be interactive or it can take all the
arguments on the commandline Tip: use PreparedStatement
Create a simple Java program that lists all persons older than a given age It can be interactive or it can take all the
arguments on the commandline Tip: use PreparedStatement