JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.

Slides:



Advertisements
Similar presentations
Database programming in Java An introduction to Java Database Connectivity (JDBC)
Advertisements

JDBC CS-328. JDBC Java API for accessing RDBMS Allows use of SQL for RDBMS programming Can be used for: –embedded SQL –execution of stored queries.
1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 Sub-queries and Views. 2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How.
1 JDBC – Java Database Connectivity Representation and Management of Data on the Internet.
1 Triggers. 2 PL/SQL reminder We presented PL/SQL- a Procedural extension to the SQL language. We reviewed the structure of an anonymous PL/SQL block:
1 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
JDBC DBI 2008 HUJI-CS 2 Java Database Connectivity JDBC (Java Database Connectiveity) is an API (Application Programming Interface), –That.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
Web Application Development Muhammad Ali Versonic Pte Asher Imtiaz Forman Christian College.
Training - Day 3 OJB. What is OR Mapping? OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
1 JDBC – Java Database Connectivity Modified slides from Dr. Yehoshua Sagiv.
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
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 Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
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.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
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.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
Chapter 8 Databases.
JDBC – Java Database Concentricity
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC (Java Database Connectivity)
CS122B: Projects in Databases and Web Applications Winter 2016
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
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.
JDBC 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql Package API:
1 JDBC – Java Database Connectivity THETOPPERSWAY.COM.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Database Activity CEMC Steps 1. Verify Data Tools Platform is installed in Eclipse 2. Configure a Connection to Derby Create necessary table for.
Java Database Connectivity: JDBC
DB Apps Introduction SoftUni Team Technical Trainers
CS3220 Web and Internet Programming Database Access with JDBC
Managing Concurrency in Web Applications
JDBC
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
How to connect natively?
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
HW#4 Making Simple BBS Using JDBC
Design and Implementation of Software for the Web
JDBC – Java Database Connectivity
Data.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

JDBC Part II CS 124

More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC and ORM

Mapping Java Types to SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp

Date and time types Times in SQL are notoriously non-standard Java defines three classes to help java.sql.Date year, month, day java.sql.Time hours, minutes, seconds java.sql.Timestamp year, month, day, hours, minutes, seconds, nanoseconds usually use this one

Dealing with types When processing a query (via executeQuery and ResultSet), you need to establish the correspondence between JDBC types and SQL types Basis for getXXX() methods for a ResultSet Good idea to also use setXXX() methods on a PreparedStatement Versus building the query string manually

Statement vs PreparedStatement Are these the same? What do they do? String val = "abc"; PreparedStatement pstmt = con.prepareStatement("select * from R where A=?"); pstmt.setString(1, val); ResultSet rs = pstmt.executeQuery(); String val = "abc"; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val);

Statement vs PreparedStatement This will result in an error Resulting SQL is select * from R where A=abc missing the quotes String val = "abc"; Statement stmt = con.createStatement( ); ResultSet rs = stmt.executeQuery("select * from R where A=" + val);

Statement vs PreparedStatement This version is OK Resulting SQL is select * from R where A=‘abc’ a PreparedStatement properly handles the data type Useful particularly for difficult types like dates/times String val = "abc"; PreparedStatement pstmt = con.prepareStatement("select * from R where A=?"); pstmt.setString(1, val); ResultSet rs = pstmt.executeQuery();

Statement vs PreparedStatement Will this work? No!!! A ‘?’ can only be used to represent a column value PreparedStatement pstmt = con.prepareStatement("select * from ?"); pstmt.setString(1, myFavoriteTableString);

Timeout Use setQueryTimeOut(int seconds) of Statement to set a timeout for the driver to wait for a statement to be completed If the operation is not completed in the given time, an SQLException is thrown What is it good for? testing query performance

NULL values In SQL, NULL means the field is empty Not the same as 0 or "" In JDBC, you must explicitly ask if the last- read field was null ResultSet.wasNull(column) For example, getInt(column) will return 0 if the value is either 0 or NULL!

NULL values When inserting null values into placeholders of Prepared Statements: Use the method setNull(index, Types.sqlType) for primitive types (e.g. INTEGER, REAL ); You may also use the set (index, null) for object types (e.g. STRING, DATE ).

ResultSet meta-data ResultSetMetaData rsmd = rs.getMetaData(); int numcols = rsmd.getColumnCount(); for (int i = 1 ; i <= numcols; i++) { System.out.print(rsmd.getColumnLabel(i)+" "); } A ResultSetMetaData is an object that can be used to get information about the properties of the columns in a ResultSet object An example: write the columns of the result set

Calling close() on objects Remember to close the Connections, Statements, Prepared Statements and Result Sets Forgetting these can result in unpredictable results, though generally it results in an OutOfMemoryError if done too many times con.close(); stmt.close(); pstmt.close(); rs.close()

Dealing With Exceptions An SQLException is actually a list of exceptions catch (SQLException e) { while (e != null) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); e = e.getNextException(); }

Transactions and JDBC Transaction: more than one statement that must all succeed (or all fail) together e.g., updating several tables due to customer purchase If one fails, the system must reverse all previous actions Also can’t leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = cancel all actions

Example Suppose we want to transfer money from bank account 13 to account 72: PreparedStatement pstmt = con.prepareStatement("update BankAccount set amount = amount + ? where accountId = ?"); pstmt.setInt(1,-100); pstmt.setInt(2, 13); pstmt.executeUpdate(); pstmt.setInt(1, 100); pstmt.setInt(2, 72); pstmt.executeUpdate(); What happens if this last update fails?

Transaction Management Transactions are not explicitly opened and closed The connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed as they are executed if AutoCommit is false, then every statement is added to an ongoing transaction Default: true

AutoCommit on Connection If you set AutoCommit to false, you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() Note: DDL statements (e.g., creating/deleting tables) in a transaction may be ignored or may cause a commit to occur The behavior is DBMS dependent setAutoCommit(boolean val)

JDBC usage in industry JDBC as you can see is very cumbersome coding wise especially for systems with many queries and many tables Over the years, Object Relational Mapping (ORM) software have been created to simplify the use of JDBC generally, most externalize the mappings of JDBC table columns to java objects and provide simpler API for common CRUD operations Some ORM software: Apache iBatis ( Hibernate (