Database programming in Java An introduction to Java Database Connectivity (JDBC)

Slides:



Advertisements
Similar presentations
Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
Advertisements

Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
1 Java DataBase Connectivity JDBC java.sql.*. 2 Java DataBase Connectivity Draft release of JDBC spec (3/96) Java API for executing SQL statements (Since.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
CS 405G: Introduction to Database Systems Database programming.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC – Java DataBase Connectivity. JDBC API Overview JDBC is Java API that allows the Java programmers to access database management system from Java.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Basics of JDBC.
Basics of JDBC Session 14.
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 8: Applications Programming for Relational Databases Instructor’s.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
JDBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
DEPTT. OF COMP. SC & APPLICATIONS
Interacting with Database
Lec - 14.
JDBC 15-Apr-18.
JDBC 21-Aug-18.
Introduction to Programming with Java
JDBC 15-Nov-18.
Interacting with Database
JDBC – ODBC DRIVERS.
Java Database Connectivity
Java API for Database Connectivity
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Database programming in Java An introduction to Java Database Connectivity (JDBC)

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

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

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

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

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

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

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

java.sql.DriverManager The DriverManager is responsible for loading the correct Driver The DriverManager is used to get a connection to the database

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”

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)

java.sql.Connection – important methods setAutoCommit(boolean) createStatement() prepareStatement(“SQL query”) commit() rollback() close()  ALLWAYS close your connections

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

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

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

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

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();

java.sql.CallableStatement CallableStatement is used to prepare and call stored procedures in the database prepareCall(“statement”) execute()

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

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

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

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

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/jd bc/multi1”); ds.getConnection();

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. }

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 ident 14. 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")); } 25. }

More advanced example, continued 26. 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. } } 54. }

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));

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