Database Programming With Java & JDBC Reading: DD Ch. 18, pp905-928 al/jdbc/index.html, or anything covering JDBC.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
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 CSE432 Object Oriented Software Engineering.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 PostgreSQL JDBC interface documentation
Distributed Application Development B. Ramamurthy.
1 JDBC Java Database Connectivity. 2 c.pdf
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
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.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Dale Roberts 8/24/ Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
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.
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.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Database Programming in Java Corresponds with Chapter 32, 33.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
CS 405G: Introduction to Database Systems Database programming.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Chapter 8 Databases.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
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. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
DAT602 Database Application Development Lecture 9 Advanced JDBC 2.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
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.
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.
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.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
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.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC Session 14.
JDBC - Resultset The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the.
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC – Java DataBase Connectivity
Lec - 14.
Course Outcomes of Advanced Java Programming AJP (17625, C603)
JDBC – Java Database Connectivity
Design and Implementation of Software for the Web
JDBC – Java DataBase Connectivity
JDBC – Java DataBase Connectivity
Introduction to Server-Side Web Development using JSP and Databases
Objectives In this lesson, you will learn about:
Interacting with Database
JDBC – Java DataBase Connectivity
Presentation transcript:

Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC

Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn Why connecting via a db is important The components of the JDBC interface to DBMSs How to connect to a database from Java How to send SQL statements from Java to a DBMS The concepts of the ResultSet object and what a Cursor is How to navigate and update a ResultSet from Java

Dept. of Computing Science, University of Aberdeen3 JDBC: Java Database Connectivity API for Java which defines how program can access a db JDBC(TM) - developed by Sun Microsystems Exploited an existing interface library (ODBC) ODBC - Open Database Connectivity (C library)—standard Application Programming Interface for connecting to db; independent of programming languages, db systems, OS ODBC - C programmers DB interface, early 1990's

Dept. of Computing Science, University of Aberdeen4 The JDBC Programming Model The JDBC uses a client-server programming model: – Client makes a connection to the DB (the server) – Client sends SQL statement(s) (query) to the DB – Can manipulate database metadata (info about tables, data types, information schema etc.) – DB sends back a Result Set – Client processes Result Set – Client disconnects from the DB Points to note: – Result Set includes query results and metadata – JDBC throws an exception whenever there's an error

Dept. of Computing Science, University of Aberdeen5 JDBC Drivers Client-side adaptors that convert Java program requests into a protocol that DBMS understands 4 types: 1.Type 1—JDBC-ODBC bridge 2.Type 2—Native API driver (converts JDBC calls to DBMS API) 3.Type 3—Network protocol driver—can connect JDBC to middleware-net server 4.Type 4—Driver-native protocol driver (converts JDBC calls directly to DBMS protocol)

Dept. of Computing Science, University of Aberdeen6 Loading a DriverManager DriverManager provides DB interface methods & defines objects which can connect Java app to driver; it manages set of drivers program can use to connect to db; finds driver & runs it to connect to db Most Java programs use import to load a class With JDBC, usually load driver class at runtime: import java.lang.*; public static void main (String args[]) { try { // this loads & initialises the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // now connect to DB... } catch (ClassNotFoundException e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); }

Dept. of Computing Science, University of Aberdeen7 Making a JDBC-ODBC Database Connection import java.sql.*; Connection con; String URL = "jdbc:odbc:DataSource"; String Username = ""; String Password = ""; con = DriverManager.getConnection(URL,Username, Password); // make more calls to JDBC methods here... con.close(); ‘DataSource’ is a ‘logical name’ (not a real filename) Need to set DataSource = MyDatabase.mdb elsewhere Use ODBC Data Source Administrator for this...

Dept. of Computing Science, University of Aberdeen8 Statement and ResultSet Objects Statement stmt = con.createStatement(); String sql = "SELECT * FROM Staff;"; ResultSet rs = stmt.executeQuery(sql); print_rs(rs); // shown later rs.close(); // free memory stmt.close(); Statement objects let you execute SQL queries: 3 types: Statement (simple, no parameters), Prepared Statement (precompiled queries), Callable Statement (execute call to db stored sql procedure) Can pass any legal SQL query to executeQuery() Here, rs holds the entire results table (Staff)...

Dept. of Computing Science, University of Aberdeen9 ResultSets and Cursors Each ResultSet contains: – Numbered Fields (columns) – Field names & types (metadata) – A Cursor (current row) The ResultSet object is a ‘container’ for the results of a query (table): First cursor position is BEFORE FIRST ROW Rows and columns COUNT FROM ONE Move cursor via: rs.next(), previous(), first(), last(), relative(), absolute(), beforeFirst(), afterLast()

Dept. of Computing Science, University of Aberdeen10 ResultSet Metadata We can find the number of columns, the column names and data types (REAL, CHAR, etc.) from the ResultSet metadata: ResultSetMetaData md = rs.getMetaData(); int num_columns = md.getColumnCount(); for (int i=1; i<=num_columns; i++) { System.out.println("Column Number = " + i); System.out.println("Column Name = " + md.getColumnLabel(i)); System.out.println("Column Type = " + md.getColumnTypeName(i)); }

Dept. of Computing Science, University of Aberdeen11 Example: Printing a ResultSet We can move through the rows using the next() method: private void print_rs(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getMetaData(); int num_columns = md.getColumnCount(); while (rs.next()) { String row_buffer = ""; for (int i=1; i<=num_columns; i++) { row_buffer += row_buffer + " " + rs.getString(i); } System.out.println(row_buffer); } Note use of metadata and getString() method

Dept. of Computing Science, University of Aberdeen12 Handling ResultSet Field Types There is a ‘get’ function for each of the main SQL data types (each needs a column no. or a column name): – rs.getString(index) – getInt() – getDouble() – getDate() – in general getxxxx() To do arithmetic on field values, need to extract into appropriate type: –double ave = rs.getDouble("Rent") /rs.getInt("Rooms");

Dept. of Computing Science, University of Aberdeen13 Updatable & Scrollable Cursors There are several types of ‘cursor’. The type we get is controlled by the call to createStatement(): stmt = con.createStatement(int scrolling, int concurrency); scrolling: – ResultSet.TYPE_FORWARD_ONLY - the default! – ResultSet.TYPE_SCROLL_INSENSITIVE – cursor can move forward & backward – ResultSet.TYPE_SCROLL_SENSITIVE – advanced; sensitive to changes made by other users concurrency: can RS be updated? – ResultSet.CONCUR_READ_ONLY - the default! RS can’t be updated – ResultSet.CONCUR_UPDATABLE—RS can be updated, & these changes can be placed into underlying DB

Dept. of Computing Science, University of Aberdeen14 Scrollable Cursor Method Functions Scrollable cursors have a rich set of method functions: – Boolean next(), previous() – void absolute(int row_num), –void relative(int row_increment), – Boolean first(), last() – void beforeFirst(), afterLast() You can also ask where the cursor is currently positioned: – Boolean isFirst(), isLast() – Boolean isBeforeFirst(), isAfterLast()

Dept. of Computing Science, University of Aberdeen15 Inserting or Deleting Rows For queries that do not return a ResultSet, use the executeUpdate(sql) method: Statement stmt = con.createStatement(); String sql = "DELETE FROM Client " + "WHERE ClientNo = " + "'CR56';"; int num_rows = stmt.executeUpdate(sql); Returns int (row count for insert, update, delete queries, 0 for sql stmts that return nothing) If successful, get num_rows = 1 (no. rows changed) Could use "INSERT INTO Client..." in the same way... Health warning: – TAKE SPECIAL CARE WITH SPACES AND QUOTES

Dept. of Computing Science, University of Aberdeen16 Updating an Existing Row To update a row, first get it into the ResultSet: Statement stmt = con.createStatement(); String code = "CR56"; String sql = "SELECT * FROM Client" +" WHERE ClientNo ="+ " '" + code + "'" + ";"; ResultSet rs = stmt.executeQuery(sql); rs.absolute(1); // move to first row rs.updateDouble("MaxRent", 500.0); rs.updateString("PrefType", "House"); rs.updateRow(); rs.close(); Here, ResultSet must contain the primary key - why? Also, note that ResultSet must be CONCUR_UPDATEABLE rs.insertRow() etc.

Dept. of Computing Science, University of Aberdeen17 Handling NULLs The JDBC API handles NULLs using a special method function: wasNull() – Have to "get" a field value, and then test for NULL... String x = rs.getString("City"); if (rs.wasNull()) x = "NULL"; int i = rs.getInt("Rooms"); if (rs.wasNull()) i = -1; // or whatever Your code can then test for special value later...

Dept. of Computing Science, University of Aberdeen18 Summary Programming model: Client (Java) sends SQL strings to server (DBMS) Server (DBMS) sends a ResultSet back to client... Programming features: JDBC is strongly typed: getString(), getInt()... JDBC throws exceptions whenever there's a error Consider type of cursor: scrollable/updateable? ResultSet rows & columns count from ONE ResultSet cursor starts BEFORE the first row Some ResultSets are updateable, so changes from Java program on ResultSet (if concur_updateable) can be committed to db