JDBC Overview. Java Database Connectivity. Gregg Lippa Senior Technical Analyst Themis Education Themis, Inc.

Size: px
Start display at page:

Download "JDBC Overview. Java Database Connectivity. Gregg Lippa Senior Technical Analyst Themis Education Themis, Inc."

Transcription

1 JDBC Overview Java Database Connectivity Gregg Lippa Senior Technical Analyst Themis Education Themis, Inc. Visit us at: Also:

2 This Webinar Addresses These Questions How do you access relational data in Java using JDBC? What is a JDBC driver and how do you use it? How do you make a connection to a database? What are Statements and PreparedStatements? How do prepared statements improve performance? How do you process database query results? How do you handle JDBC exceptions and warnings? How do you call stored procedures using JDBC? How does JDBC support database transactions? How do you specify isolation levels via JDBC? What are ORM, JPA and Hibernate and what do they do? We will have very little time for questions Please submit questions via to glippa@themisinc.com 2

3 Static SQL vs Dynamic SQL Static SQL: compiled and bound to database during application development Dynamic SQL: compiled and optimized at runtime Increases total statement execution time Errors in the SQL statement not detected until runtime Benefits of Static SQL Compile at bind time allows for efficient access path/plan selection Security can be applied at the plan level Disadvantages of Static SQL Need to bind before runtime and manage plans that are created JDBC does not provide support, except through Stored Procedures SQLJ does support this but is not widely used (nor covered today) 3

4 Static SQL vs Dynamic SQL Benefits of Dynamic SQL IDEs and APIs such as Eclipse and JDBC support dynamic SQL Better statistics because the statement is compiled at runtime Uses the latest statistics available May result in a better execution plan Disadvantages of Dynamic SQL Compile at runtime can be a problem for several reasons: Every time a statement is executed, it needs to be compiled, which increases the total statement execution time Since the compile time figures into the total execution time, even with higher optimization levels, overall performance may degrade instead of improving Because the SQL statement is not compiled until runtime, errors in the SQL will not be detected until runtime To summarize: Use Static SQL if security and/or performance is your major concern Use Dynamic SQL if ease of development is your main concern 4

5 Stored Procedures Precoded SQL, usually contained within programming logic Supports static SQL when using JDBC Highly recommended in the financial industry Less vulnerable to attacks Can be written with static SQL JDBC can be used to call Stored Procedures We will see how to call a Stored Procedures using JDBC We will not see how to write the actual Stored Procedure (SP) Each DBMS provides its own language support for writing SPs Some SPs can be written in commercial languages, such as COBOL 5

6 JDBC: Java Database Connectivity Trademarked name of technology written by Sun Now owned by Oracle Framework composed mainly of interfaces Defined by Sun and implemented by database drivers Same functionality available regardless of driver Switching databases should require minimal code changes Java Application Programming Interface (API) Provides access to any type of tabular data Normally used to access Relational Databases Vendor independent Allows Java applications to easily Connect to data source Create and execute queries and updates Retrieve and process query results 6

7 JDBC: Three-tier Architectures Three-tier Architecture for Data Access Client HTML Browser or Java Applet HTTP, RMI, CORBA Application Server Java Application or Servlet JDBC API Browser communicates with a middle tier which in turn communicates with data source Driver DBMS-Proprietary Protocol Database Server DBMS 7

8 JDBC Drivers Java Application Code JDBC Driver Manager JDBC-ODBC Bridge ODBC Driver Manager ODBC Driver (MS Access) ODBC Driver (MySQL) JDBC Driver (Oracle) JDBC Driver (DB2) DBMS (Access) DBMS (MySQL) DBMS (Oracle) DBMS (DB2) 8

9 Database Access Overview 1. Obtain connection to data source Load and use a database driver to connect Alternatively, use connection pooling (later) 2. Perform database activities Create a JDBC Statement object Execute SQL performing query or update Retrieve and process query results or retrieve update counts 3. Terminate connection to data source Close all database-related objects 9

10 Load Database Driver Connecting to a data source requires an appropriate database driver Driver is specific to database being used Usually provided by database vendor forname: static method defined in Class class Takes one parameter: name of the driver class Loads the specified database driver class Results in registration of driver with DriverManager May throw ClassNotFoundException Examples: try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); catch(classnotfoundexception e) { // handle problem loading driver here Load Sun s JDBC-ODBC bridge driver try { Class.forName("com.ibm.db2.jcc.DB2Driver"); catch(classnotfoundexception e) { // hadle problem loading DB2 driver here Load DB2 driver 10

11 Connect to Data Source DriverManager class provides services for managing drivers DataSource provides alternative way to connect (more later) Use its static getconnection method to open connection Returns a Connection object supporting specified database URL Throws SQLException if problem connecting Optionally accepts userid and password parameters Database URL depends on driver being used URL consists of: jdbc:subprotocol:subname jdbc subprotocol subname Main Protocol Driver specific Driver specific Connection conn = null; try { conn = DriverManager.getConnection( "jdbc:dburl:dbname","dbid","dbpw"); catch(sqlexception e) { // handle database connection problems Open connection to database providing an id and password 11

12 Connecting to Data Source Example import java.sql.*; public class MySQLConnect { public static void main(string [] args) { System.out.println("DB2 Connect Example."); Connection conn = null; String dburl = "jdbc:db2://p390.themisinc.com:50000/db1a"; String driver = "com.ibm.db2.jcc.db2driver"; String username = "user1"; //never hard code String password = "mypasswd"; //in your program try { // load driver and get connection Class.forName(driver); conn = DriverManager.getConnection(dburl, username, password); // this is where you use the database connection now available System.out.println("Successfully connected to DB: " + dburl); catch(classnotfoundexception e) { System.err.println("Cannot find JDBC Driver named " + driver); catch(sqlexception e) { System.err.println("Cannot make Connection to " + dburl); finally { try { // explicitly close Connection when finished to release resources conn.close(); System.out.println("Disconnected from database"); catch(sqlexeception e) { System.err.println("Close error for " + dbname + e.getmessage()); 12

13 Create Statement Connection provides createstatement method Returns Statement object used to interact with the database via SQL May throw SQLException Accepts two optional configuration parameters supporting: 1. Scrollable cursors 2. Updateable ResultSets Example: // Create Statement for sending SQL to database Statement stmt = null; try { Defaults to a cursor that is stmt = conn.createstatement(); forward only and read only catch(sqlexception e) { // handle problem creating statement 13

14 Executing SQL Statement object is used to execute SQL on database Use executequery method to execute database query (SELECT) Passed a parameter containing SQL to execute Returns a ResultSet object for processing selected rows Returns empty ResultSet object if nothing selected Use executeupdate method to modify database Both methods are defined in Statement Passed a parameter containing SQL to execute (non-select) Returns int corresponding to: Row count for DML statements (INSERT, UPDATE, DELETE) Zero (0) for DDL statement (CREATE, ALTER, DROP, etc.) ResultSet rs = null; int rowcount = 0; try { rs = stmt.executequery("select * from Product Where name like 'S%'"); rowcount = stmt.executeupdate("delete from Product where id = 1234"); catch(sqlexception e) { // handle problems executing SQL 14

15 Result Sets ResultSet object is returned from executequery method May be Scrollable and/or updateable depending on how Statement was created Optional parameters may be passed to createstatement If parameters omitted, createstatement defaults to TYPE_FORWARD_ONLY and CONCUR_READ_ONLY ResultSet types available: TYPE_FORWARD_ONLY (Default) TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE Result set not scrollable Cursor moves forward only (from before first row to after last row) Most efficient Result set scrollable (cannot see concurrent changes made by others) Cursor can move both forward and backward relative to current position (relative method) Cursor can move to absolute position (absolute method) Result set scrollable (can see concurrent changes made by others) Cursor can move both forward and backward relative to current position (relative method) Cursor can move to absolute position (absolute method) Least efficient (avoid if possible) ResultSet concurrencies: CONCUR_READ_ONLY (Default) CONCUR_UPDATABLE Result set may not be updated Result set may be updated 15

16 Cursor Positioning ResultSet supports cursor positioning Columns are retrieved from row referenced by cursor Cursor initially positioned before first row (no data available) Scrollable cursors support unlimited movement Cursor positioning methods of ResultSet Only the next() method is available by default Cursor Positioning Method boolean next() boolean previous() boolean first() boolean last() void beforefirst() void afterlast() boolean relative(int rows) boolean absolute(int row) Effect on Cursor Moves cursor forward one row from current position Moves cursor up (backwards) to previous row Moves cursor to first row Moves cursor to last row Moves cursor to front (just before first row) Moves cursor to end (just after last row) Moves cursor relative to current position Positive value moves cursor forward Negative value moves cursor backward Moves cursor to specified row number Positive moves cursor with respect to beginning Negative value moves cursor with respect to end 16

17 Cursor Positioning Example Statement sql = null; ResultSet rs; sql = conn.createstatement(resultset.type_scroll_insensitive, ResultSet.CONCUR_READ_ONLY); rs = sql.executequery("select * From Product"); // position cursor after last row rs.afterlast(); // process ResultSet from back to front while(rs.previous()) { // process current row here rs.absolute(4); rs.relative(-2); rs.relative(3); Scrollable cursor created so all positioning methods are available previous method returns false when the cursor is positioned before 1 st row 17

18 Column Retrieval ResultSet defines getter methods to retrieve column values Column values individually retrieved using either: String containing column name (not case sensitive) int containing column number (position in SELECT statement) JDBC type converted to Java type by driver if possible Use appropriate method depending on data type getstring can convert simple types to String value Examples: Getter Method JDBC Type Java Type getstring [VAR]CHAR String getdouble DOUBLE double getfloat FLOAT float getbigdecimal NUMERIC BigDecimal getbigdecimal DECIMAL BigDecimal getlong BIGINT long getint INTEGER int getshort SMALLINT short getbyte TINYINT byte getboolean BIT boolean getbytes [VAR]BINARY byte [] getdate DATE java.sql.date gettime TIME Time gettimestamp TIMESTAMP Timestamp getsqlxml SQLXML java.sql.sqlxml // get column cost as BigDecimal value BigDecimal price = rs.getbigdecimal("cost"); // get 3 rd column in SELECT as String value String name = rs.getstring(3); JDBC Types are defined in java.sql.types 18

19 Result Sets Handling Null Values Column values retrieved from a ResultSet may be null The getxxx methods of ResultSet will set the variable receiving the value to Null if it is a reference variable (e.g. BigDecimal, String, Date) Zero (0) if it is a primitive type variable Methods like getdate and getstring will therefore possibly return null Testing for null values in the column is simply a matter of checking for null Methods like getdouble and getint return zero if column value was null No SQLException is thrown For primitive type data, use the wasnull method after the getxxx call Returns a boolean indicating whether the last column read had a value of SQL null This call must be the next call made to the ResultSet following the getxxx call // BigDecimal column cost may be null BigDecimal price = rs.getbigdecimal("cost"); if (price == null) { /* handle null value here */ // Integer column quantity may be null double qty = rs.getdouble("quantity"); if (rs.wasnull()) { /* handle null value here */ 19

20 Updatable Result Sets Update methods are available to update columns in result set Provided in ResultSet but not supported by all drivers and DBMS JDBC type determines method Updates apply to current row (based on cursor position) Modifies ResultSet (not database table) updaterow causes update of row in database table cancelrowupdates cancels (prevents) update deleterow deletes row from ResultSet and database Update method parameters include: Column label (name) or index Column value (same type as in DB) Update method examples for int: myrs.updateint(3, 1000) myrs.updateint("quantity", 25) An update method exists for each supported JDBC type 20

21 Updatable ResultSet Example int quantity; Statement stmt; ResultSet rs; stmt = conn.createstatement(resultset.type_forward_only, rs = stmt.executequery( "Select * from Product"); while(rs.next()) { quantity = rs.getint("qtyonhand"); quantity += 10; rs.updateint("qtyonhand", quantity); rs.updaterow(); ResultSet.CONCUR_UPDATABLE); Statement must be created as CONCUR_UPDATABLE Select must access single table only 21

22 Complete JDBC Example package jdbc; public class UseDatabase { public static void main(string[] args) { System.out.println("Using Access database"); ProductTable accessdb = new ProductTable( "jdbc:odbc:javaapp", "sun.jdbc.odbc.jdbcodbcdriver"); accessdb.createconnection(); accessdb.insertproduct(123, "Uni Widget", 10); accessdb.insertproduct(456, "Left Widget", 3); accessdb.insertproduct(789, "Right Widget", 6); accessdb.showallproducts(); accessdb.shutdown(); OUTPUT Using Access database row inserted for Uni Widget row inserted for Left Widget row inserted for Right Widget ID Name Quantity Uni Widget Left Widget Right Widget 6 System.out.println("\nUsing DB2 database"); ProductTable mydb2 = new ProductTable( "jdbc:db2://p390.themisinc.com:50000/db1a", "com.ibm.db2.jcc.db2driver"); mydb2.createconnection("user1", "mypasswd"); mydb2.insertproduct(123, "Uni Widget", 10); mydb2.insertproduct(456, "Left Widget", 3); mydb2.insertproduct(789, "Right Widget", 6); mydb2.showallproducts(); mydb2.shutdown(); Methods being called in above code are defined on the 4 following pages Using DB2 database row inserted for Uni Widget row inserted for Left Widget row inserted for Right Widget ID Name Quantity Uni Widget Left Widget Right Widget 6 22

23 ProductTable Class and Constructor package jdbc; import java.sql.*; public class ProductTable { private String dburl = null; private String driver = null; private Connection conn = null; private Statement stmt = null; public ProductTable( String dburl, String driver) { this.dburl = dburl; this.driver = driver; Access DB2 dburl jdbc:odbc:javaapp jdbc:db2://p390.themisinc.com:50000/db1a driver sun.jdbc.odbc.jdbcodbcdriver com.ibm.db2.jcc.db2driver 23

24 Overloaded createconnection public void createconnection() { try { // load driver and connect to database Class.forName(driver); conn = DriverManager.getConnection(dbURL); catch(classnotfoundexception e) { System.err.println("Driver load error: " + e.getmessage()); e.printstacktrace(); catch(sqlexception e) { System.err.println("DB connect error: " + e.getmessage()); e.printstacktrace(); public void createconnection(string userid, String password) { try { // load driver and connect to database Class.forName(driver); conn = DriverManager.getConnection(dbURL, userid, password); catch(classnotfoundexception e) { System.err.println("Driver load error: " + e.getmessage()); e.printstacktrace(); catch(sqlexception e) { System.err.println("DB connect error: " + e.getmessage()); e.printstacktrace(); 24

25 showallproducts Method public void showallproducts() { try { stmt = conn.createstatement(); ResultSet rs = stmt.executequery("select * from Product"); System.out.println("\nID Name Quantity"); System.out.println(" "); while(rs.next()) { System.out.print(rs.getInt("id") + "\t"); System.out.print(rs.getString("name") + "\t"); System.out.println(rs.getInt(3)); catch(sqlexception e) { System.err.println("DB statement error: " + e.getmessage()); e.printstacktrace(); finally { try { if (rs!= null) rs.close(); if (stmt!= null) stmt.close(); catch(sqlexception e) { /* handle it */ 25

26 public void insertproduct(int id, String name, int quantity) { try { // delete it first, then insert stmt = conn.createstatement(); String sql = "delete from product where id = " + id; insertproduct and shutdown stmt.executeupdate(sql); sql = "insert into product values (" + id + ", '" + name + "', " + quantity + ")"; if (stmt.executeupdate(sql) == 1) { System.out.println("row inserted for " + name); catch(sqlexception e) { System.err.println("DB error: " + e.getmessage()); e.printstacktrace(); finally { try { if (stmt!= null) stmt.close(); catch(sqlexception e) { /* handle it */ public void shutdown() { try { if(conn!= null) conn.close(); catch(sqlexception e) { /* handle it, e.g. log it */ close releases database and JDBC resources Executes the insert and checks for success 26

27 Method to Produce a List of Products public List<Product> getproductlist() { try { List<Product> productlist = new ArrayList<Product>(); stmt = conn.createstatement(); ResultSet rs = stmt.executequery("select * from Product"); while(rs.next()) { Product p = new Product(); Create a product object p.setid(rs.getint("id")); p.setname(rs.getstring("name")); Populate it with data p.setquantity(rs.getint("quantity")); from the current row productlist.add(p); Add it to the List that will be returned to the caller catch(sqlexception e) { System.err.println("DB statement error: " + e.getmessage()); finally { try { if (rs!= null) rs.close(); if (stmt!= null) stmt.close(); if (conn!= null) conn.close(); catch (SQLException e) { /* handle it */ return productlist; // sample call to the above method List<Product> theresults = null; theresults = getproductlist(); for (Product p : theresults) {... 27

28 PreparedStatement Interface PreparedStatement precompiles SQL for repeated use SQL is supplied when PreparedStatement created Unlike Statement, which receives its SQL at execution time Supplied SQL may contains one or more question marks (?) These are placeholders for parameters which must be supplied Calls to setxxx methods specify their values Create via preparestatement method of Connection Requires the SQL statement as a parameter Optionally supports scrollability and updateability String sql = "Select * From Product Where name =?" PreparedStatement pstmt = conn.preparestatement(sql); pstmt.setstring(1, "Left Widget"); ResultSet rs = pstmt.executequery(); 28

29 PreparedStatement To Delete Rows public void deleterows() { int totaldeleted = 0; try { // 2 parameters specified (one int and one String) String sql = "Delete From Product Where id =? AND name =?"; PreparedStatement pstmt = conn.preparestatement(sql); // file toberemoved.txt contains id and name to be deleted BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream("toBeRemoved.txt"))); String number = null; while((number = in.readline())!= null) { int id = Integer.parseInt(number); String name = in.readline(); // Use file input to set all parameter values pstmt.setint(1, id); pstmt.setstring(2, name); int deletecount = pstmt.executeupdate(); totaldeleted += deletecount; catch(exception e) { /* error handling here */ System.out.println("\nTotal rows deleted: " + totaldeleted); try { if (in!= null) in.close(); catch(ioexception e) { /* error handling here */ readline returns null on EOF Returns number of rows deleted INPUT FILE CONTENTS: 123 Uni Widget 789 Right Widget 29

30 Connection Pooling Application threads share connections Only need connection during processing of transaction Connection needed for a relatively short time Connection can then be used by another thread Benefits of connection pooling Greatly increases performance of applications Reduces connection creation time Simplifies programming Reduces resource usage May improve licensing costs Simplifies switch to a different DBMS Managed by a Java EE server Typically created using server s administrative tools Obtained via JNDI lookup Java Naming and Directory Interface 30

31 Connection Pooling Example import javax.naming.*; import javax.sql.datasource; public void createconnection(string userid, String password) { String datasourcename = "jdbc/dsnamesetbyadministrator" String localdatasourcename = "java:comp/env/jdbc/mydsname" try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(datasourcename); Connection conn = ds.getconnection(userid, password); catch(namingexception e) { /* handle exception relating to JNDI naming issue */ catch(sqlexception e) { /* handle exception relating to SQL error */ // alternative: use locally defined name to lookup DataSource DataSource ds = (DataSource) ctx.lookup(localdatasourcename); 31

32 Error Handling SQLException is a specific kind of Exception Provides additional methods specific to database access Method String getsqlstate() int geterrorcode() String getmessage() Returns Standard SQLState value Vendor-specific SQLCode value Vendor-specific error message (inherited from Throwable class) try { // SQL database work here catch(sqlexception sqle) { StringBuilder out = new StringBuilder("** SQL Error Information **\n"); out.append("sql State: ").append(sqle.getsqlstate()).append("\nerror Code: ").append(sqle.geterrorcode()).append("\nmessage: ").append(sqle.getmessage()); System.err.println(out); OUTPUT ** SQL Error Information ** SQL State: Error Code: 1049 Message: Unknown database 'unknown' 32

33 Processing Warnings SQLWarning is a specific kind of SQLException Indicates less severe SQL problem or status Warnings are not thrown (do not stop execution) They are chained silently to generating object Connection, Statement, ResultSet Must be explicitly requested using appropriate method getwarnings() returns the first SQLWarning getnextwarning() returns the next SQLWarning in the chain String dburl = "jdbc:odbc:javaclass"; Connection conn = DriverManager.getConnection(dbURL); Statement stmt = conn.createstatement(); // Process warnings on Connection object SQLWarning w = conn.getwarnings(); StringBuilder out = new StringBuilder("** SQL Warning Info **"); while(w!= null) { out.append("\nstate: ").append(w.getsqlstate()).append("\nerror Code: ").append(w.geterrorcode()).append("\nmessage: ").append(w.getmessage()); w = w.getnextwarning(); System.err.println(out); 33

34 Using Finally JDBC connects to external resources Not garbage collected Must be explicitly released to avoid potential problems close() method of connection release resources By closing the database connection Use finally block to ensure database connection is closed try { // open connection; access database; etc. catch(sqlexception e) { // process errors here finally { try { if (conn =! null) { conn.close(); catch(sqlexception e) { /* handle it */ 34

35 Calling Stored Procedures Stored Procedures (SPs) are named SQL stored in the database Provides performance and security benefits Application makes database request with simple call JDBC's CallableStatement supports executing SPs Supports IN, OUT, and INOUT parameters via placeholders (?) OUT and INOUT parameters must be registered with a type Zero or more ResultSets may be returned from a SP Use Connection interface method preparecall Requires an SQL statement containing the SP call syntax Returns a CallableStatement referring to the SP Three methods to execute Stored Procedures: executequery(), executeupdate(), execute() 35

36 Callable Statement Example public String getnameforthisid(int idtofind) { // variables used for parameter values // idtofind sent to stored procedure as IN parameter // name returned by stored procedure as OUT parameter String name = null; try { // two parameters required one int and one String // first parameter provides an id to search for and // second one receives the name for that id after execution // Escape syntax for stored procedure enclosed in curly braces. // Driver translates escape syntax into native SQL // used by database to call stored procedure. CallableStatement cstmt = conn.preparecall( " { call spownerid.getname (?,? ) " ); // set IN parameter to value of idtofind cstmt.setint(1, idtofind); // register OUT parameter as JDBC type VARCHAR cstmt.registeroutparameter(2, Types.VARCHAR); // execute the stored procedure cstmt.execute(); // retrieve value of OUT parameter as String name = cstmt.getstring(2); catch(sqlexception e) { /* handle it here */ finally { /* close connection here */ return namevalue; 36

37 Transaction Processing Most business operations require transactions Transaction: a group of related database updates Often requires multiple SQL statements All updates must succeed to achieve valid result AutoCommit is true by default Data modifications are committed immediately Use setautocommit method in Connection passing value false Turns off autocommit; transactions are then managed by methods of Connection: commit() - Finalize group of updates (make permanent) rollback() - Undo all updates since previous commit Note: With auto-commit turned off, closing a pooled connection will NOT automatically commit or roll back. Uncommitted updates will become part of the transaction of the next process that receives that connection object after its return to the pool. public class UseTransactionalUpdates { public static void main(string[] args) throws Exception { try { // load driver and get connection (not shown) conn.setautocommit(false); stmt = conn.createstatement(); stmt.executeupdate("delete from product where id = 123"); stmt.executeupdate("insert into product values (123, 'test', 20)"); conn.commit(); catch(sqlexception e) { try { conn.rollback(); catch(sqlexception e1) {/* handle it */ 37

38 Isolation level Isolation Levels Determines database locking characteristics of read operations Cannot be changed after a transaction has started on the connection All levels may not be supported by a given DBMS Use Connection methods to change and retrieve isolation level void settransactionisolation(int); int gettransactionisolation(); Isolation levels defined as constants in Connection interface: Isolation Level TRANSACTION_NONE TRANSACTION_READ_COMMITTED TRANSACTION_READ_UNCOMMITTED TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE Meaning Transactions not supported Dirty reads prevented Non-repeatable and phantom reads can occur Dirty, non-repeatable and phantom reads can occur Dirty and non-repeatable reads prevented Phantom reads can occur Dirty, non-repeatable and phantom reads prevented conn.settransactionisolation(connection.transaction_read_committed); 38

39 Object Relational Mapping (ORM) A Very Brief Introduction

40 Persistence of Objects: A Paradigm Mismatch Business data is usually stored and "persists" in a relational DBs Applications use SQL to store and retrieve the data Typically embedded within a programming language Object-oriented languages like Java support relational data access However, table rows and Java objects have different structures An object's fields must be mapped to a table's columns Objects participate in various relationships with other objects Inheritance, polymorphism, composition, collections, etc. Object identity and table identity may also differ, raising issues This is known as the object/relational paradigm mismatch Overcoming it has a cost Much Java code is often required to manually bridge the gap So....

41 Object Relational Mapping (ORM) ORM automates persistence of Java objects to relational tables Uses metadata to describe the mapping of objects to database tables Transparently transforms data from one representation to the other What does an ORM solution do? Specifies mapping metadata Performs CRUD on objects of persistent classes Supports queries that refer to classes and their properties Provides transaction support and optimization capabilities What issues are addressed by ORM? Design, definition and lifecycle of persistent classes Mapping class inheritance hierarchies to table structures Facilities for searching, sorting, and aggregating Runtime interaction between persistence logic and business objects Efficiency, especially when using joins to navigate an object graph

42 Why Use ORM? Reduces the time-consuming work of perisistence-related code Allows developers to concentrate on the business problems Reduces the amount of code required Makes the system more understandable and easier to maintain Focuses developers on business logic rather than plumbing Often improves performance Many performance optimizations are provided by ORM settings Equal performance is possible without ORM but requires greater developer expertise and additional development time Insulates application from underlying database ORM implementations typically support many DBMSs Simplifies the task of changing database vendors

43 Java Persistence API (JPA) ORM is now part of the Java specification known as JPA Maps Java classes to database tables Maps Java data types to SQL data types Provides data query and retrieval facilities Generates the SQL calls and submits them at the optimal time Relieves developer from manually creating objects from result sets Delivers database portability with very little performance overhead Hibernate is a popular open source ORM Available since 2003 Implements the JPA specification Also provides numerous extensions Other ORM implementations EclipseLink (was Oracle TopLink ) OpenJPA Many more

44 Where Do I Go From Here?

45 Learning More About Java, OO and Database Interaction Java 1 (Intro Java) and Java 2 (Intermediate Java) These courses spend two weeks in Java Standard Edition Both courses are necessary to get a complete background Java Enterprise Servlets and JSPs One week course on these critical components of Java EE Object Oriented Analysis and Design This course gives the budding OO developer a solid background in OO requirements specification and UML Many other courses depending on your environment Enterprise Java Beans (EJBs); Java Persistence API (JPA); Java Messaging Service (JMS); Java Server Faces (JSF); Web Services with Java; Design Patterns; Spring; XML; HTML; Hibernate; Struts; many more 45

46 Batch Java Execution (future webinar stay tuned)

47 Thank you for coming US Intl On-site and Public Instructor-led Hands-on Training Over 400 IT Courses Customization Available

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers. Q.1) What is, in terms of JDBC, a DataSource? A. A DataSource is the basic service for managing a set of JDBC drivers B. A DataSource is the Java representation of a physical data source C. A DataSource

More information

Lecture 2. Introduction to JDBC

Lecture 2. Introduction to JDBC Lecture 2 Introduction to JDBC Introducing JDBC According to Sun, JDBC is not an acronym, but is commonly misinterpreted to mean Java DataBase Connectivity JDBC: is an API that provides universal data

More information

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview COSC 304 Introduction to Database Systems Database Programming Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Database Programming Overview Most user interaction with

More information

PERSİSTENCE OBJECT RELATİON MAPPİNG

PERSİSTENCE OBJECT RELATİON MAPPİNG PERSİSTENCE Most of the applications require storing and retrieving objects in a persistent storage mechanism. This chapter introduces how to store and retrieve information in a persistent storage with

More information

JDBC, Transactions. Niklas Fors JDBC 1 / 38

JDBC, Transactions. Niklas Fors JDBC 1 / 38 JDBC, Transactions SQL in Programs Embedded SQL and Dynamic SQL JDBC Drivers, Connections, Statements, Prepared Statements Updates, Queries, Result Sets Transactions Niklas Fors (niklas.fors@cs.lth.se)

More information

JDBC - INTERVIEW QUESTIONS

JDBC - INTERVIEW QUESTIONS JDBC - INTERVIEW QUESTIONS http://www.tutorialspoint.com/jdbc/jdbc_interview_questions.htm Copyright tutorialspoint.com Dear readers, these JDBC Interview Questions have been designed specially to get

More information

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017 Introduction to SQL Programming Techniques CSC 375, Fall 2017 The Six Phases of a Project: Enthusiasm Disillusionment Panic Search for the Guilty Punishment of the Innocent Praise for non-participants

More information

More Database Programming. CS157A Chris Pollett Nov. 2, 2005.

More Database Programming. CS157A Chris Pollett Nov. 2, 2005. More Database Programming CS157A Chris Pollett Nov. 2, 2005. Outline JDBC SQLJ Introduction Last day we went over some JDBC and SQLJ code examples from prior classes. Today, we will discuss JDBC and SQLJ

More information

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming Objectives Java Database Connectivity JDBC basic Working with JDBC Adv anced JDBC programming By Võ Văn Hải Faculty of Information Technologies Summer 2012 2/27 Definitions of JDBC JDBC APIs, which provides

More information

Top 50 JDBC Interview Questions and Answers

Top 50 JDBC Interview Questions and Answers Top 50 JDBC Interview Questions and Answers 1) What is the JDBC? JDBC stands for Java Database Connectivity. JDBC is a Java API that communicates with the database and execute SQLquery. 2) What is a JDBC

More information

JAVA AND DATABASES. Summer 2018

JAVA AND DATABASES. Summer 2018 JAVA AND DATABASES Summer 2018 JDBC JDBC (Java Database Connectivity) an API for working with databases in Java (works with any tabular data, but focuses on relational databases) Works with 3 basic actions:

More information

Database Application Development

Database Application Development Database Application Development Linda Wu (CMPT 354 2004-2) Topics SQL in application code Embedded SQL JDBC SQLJ Stored procedures Chapter 6 CMPT 354 2004-2 2 SQL in Application Code SQL commands can

More information

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection. JDBC PROGRAMMING JDBC JDBC Java DataBase Connectivity Useful for database driven applications Standard API for accessing relational databases Compatible with wide range of databases Current Version JDBC

More information

SQL in a Server Environment

SQL in a Server Environment SQL in a Server Environment Vaidė Narváez Computer Information Systems January 13th, 2011 The Three-Tier Architecture Application logic components Copyright c 2009 Pearson Education, Inc. Publishing as

More information

UNIT III - JDBC Two Marks

UNIT III - JDBC Two Marks UNIT III - JDBC Two Marks 1.What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for databaseindependent connectivity between the Java programming language and a wide

More information

Unit 2 JDBC Programming

Unit 2 JDBC Programming Q1. What is JDBC? Explain the types of JDBC drivers? Ans. What is JDBC? JDBC is an API, which is used in java programming for interacting with database. JDBC (Java DataBase Connection) is the standard

More information

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Java Database Connectivity (JDBC) 25.1 What is JDBC? PART 25 Java Database Connectivity (JDBC) 25.1 What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming

More information

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets Course Name: Advanced Java Lecture 13 Topics to be covered The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets Introducing

More information

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Application Programming for Relational Databases

Application Programming for Relational Databases Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California shahabi@usc.edu 1 Overview JDBC Package Connecting to databases with JDBC Executing

More information

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal Introduction JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC standard is defined by Sun Microsystems and implemented through the standard

More information

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Database Connection Budditha Hettige Department of Statistics and Computer Science Budditha Hettige 1 From database to Java There are many brands of database: Microsoft

More information

JDBC Installation Transactions Metadata

JDBC Installation Transactions Metadata Course Name: Advanced Java Lecture 14 Topics to be covered JDBC Installation Transactions Metadata Steps in JDBC Connectivity:Connectivity:Here are the JDBC Steps to be followed while writing JDBC

More information

Databases 2012 Embedded SQL

Databases 2012 Embedded SQL Databases 2012 Christian S. Jensen Computer Science, Aarhus University SQL is rarely written as ad-hoc queries using the generic SQL interface The typical scenario: client server database SQL is embedded

More information

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets JDBC Stands for Java Database Connectivity, is an API specification that defines the following: 1. How to interact with database/data-source from Java applets, apps, servlets 2. How to use JDBC drivers

More information

SNS COLLEGE OF ENGINEERING, Coimbatore

SNS COLLEGE OF ENGINEERING, Coimbatore SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 03 JDBC JDBC Overview JDBC implementation

More information

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.) Overview Database Application Development Chapter 6 Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures Database Management Systems 3ed

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 Database Management Systems 3ed 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 Database Management Systems 3ed 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic SQL JDBC SQLJ Stored procedures

More information

JDBC 3.0. Java Database Connectivity. 1 Java

JDBC 3.0. Java Database Connectivity. 1 Java JDBC 3.0 Database Connectivity 1 Contents 1 JDBC API 2 JDBC Architecture 3 Steps to code 4 Code 5 How to configure the DSN for ODBC Driver for MS-Access 6 Driver Types 7 JDBC-ODBC Bridge 8 Disadvantages

More information

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation Kyle Brown Knowledge Systems Corporation 1 What is the JDBC? What other persistence mechanisms are available? What facilities does it offer? How is it used? 2 JDBC is the Java DataBase Connectivity specification

More information

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200 Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200 1 SQL code in other programming languages SQL commands can be called from within a host language (e.g., C++ or Java) program.

More information

Chapter 16: Databases

Chapter 16: Databases Chapter 16: Databases Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 16 discusses the following main topics: Introduction to Database

More information

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Database Access with JDBC Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Overview Overview of JDBC technology JDBC drivers Seven basic steps in using JDBC Retrieving

More information

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import Introduction to JDBC JDBC: Java Database Connectivity JDBC is used for accessing databases from Java applications Information is transferred from relations to objects and vice-versa databases optimized

More information

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the Agenda Lecture (07) Database connectivity (II) Connecting DB Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems 2 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems The

More information

Unit 3 - Java Data Base Connectivity

Unit 3 - Java Data Base Connectivity Two-Tier Database Design The two-tier is based on Client-Server architecture. The direct communication takes place between client and server. There is no mediator between client and server. Because of

More information

Database connectivity (II)

Database connectivity (II) Lecture (07) Database connectivity (II) Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems Agenda Connecting DB 2 Dr. Ahmed ElShafee, ACU Spring 2011, Distributed Systems The

More information

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } JDBC ("Java Database Connectivity ) is a set

More information

SQL and Java. Database Systems Lecture 20 Natasha Alechina

SQL and Java. Database Systems Lecture 20 Natasha Alechina Database Systems Lecture 20 Natasha Alechina In this Lecture SQL in Java SQL from within other Languages SQL, Java, and JDBC For More Information Sun Java tutorial: http://java.sun.com/docs/books/tutorial/jdbc

More information

Self-test Database application programming with JDBC

Self-test Database application programming with JDBC Self-test Database application programming with JDBC Document: e1216test.fm 16 January 2018 ABIS Training & Consulting Diestsevest 32 / 4b B-3000 Leuven Belgium TRAINING & CONSULTING INTRODUCTION TO THE

More information

O ne of the most important features of JavaServer

O ne of the most important features of JavaServer INTRODUCTION TO DATABASES O ne of the most important features of JavaServer Pages technology is the ability to connect to a Databases store and efficiently manage large collections of information. JSP

More information

JDBC Programming: Intro

JDBC Programming: Intro JDBC Programming: Intro Most interaction with DB is not via interactive interface Most people interact via 1. Application programs directly 2. Apps over the internet There are 3 general approaches to developing

More information

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text Learning Objectives This module gives an introduction about Java Database

More information

Database Programming. Week 9. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Database Programming. Week 9. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford Database Programming Week 9 *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford SQL in Real Programs We have seen only how SQL is used at the generic query interface

More information

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC Topic 12: Database Programming using JDBC Database & DBMS SQL JDBC Database A database is an integrated collection of logically related records or files consolidated into a common pool that provides data

More information

SQL: Programming Midterm in class next Thursday (October 5)

SQL: Programming Midterm in class next Thursday (October 5) Announcements (September 28) 2 Homework #1 graded Homework #2 due today Solution available this weekend SQL: Programming Midterm in class next Thursday (October 5) Open book, open notes Format similar

More information

Introduction to Databases

Introduction to Databases JAVA JDBC Introduction to Databases Assuming you drove the same number of miles per month, gas is getting pricey - maybe it is time to get a Prius. You are eating out more month to month (or the price

More information

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem ECS-503 Object Oriented Techniques UNIT-5 Course Jdbc... 1 Servlets... 17 JDBC --> The database is the heart of any enterpries system which is used to store and retrieve the data of enterprise more efficiently.

More information

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: How many types of JDBC Drivers are present and what are they? JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type

More information

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 - CMPUT 391 Database Management Systems JDBC in Review - - Department of Computing Science University of Alberta What Is JDBC? JDBC is a programming interface JDBC allows developers using java to gain access

More information

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. JDBC Drivers Type 1 What is JDBC Driver? JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server. For example, using JDBC drivers enable you to open database

More information

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002 Java and the Java DataBase Connectivity (JDBC) API Todd Kaufman April 25, 2002 Agenda BIO Java JDBC References Q&A Speaker 4 years Java experience 4 years JDBC experience 3 years J2EE experience BS from

More information

Persistency Patterns. Repository and DAO

Persistency Patterns. Repository and DAO Persistency Patterns Repository and DAO 1 Repository pattern Basically, the Repository pattern just means putting a façade over your persistence system so that you can shield the rest of your application

More information

Non-interactive SQL. EECS Introduction to Database Management Systems

Non-interactive SQL. EECS Introduction to Database Management Systems Non-interactive SQL EECS3421 - Introduction to Database Management Systems Using a Database Interactive SQL: Statements typed in from terminal; DBMS outputs to screen. Interactive SQL is inadequate in

More information

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree BUSINESS INTELLIGENCE LABORATORY Data Access: Relational Data Bases Business Informatics Degree RDBMS data access 2 Protocols and API ODBC, OLE DB, ADO, ADO.NET, JDBC JDBC Programming Java classes java.sql

More information

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database Outline Lecture 10: Database Connectivity -JDBC Persistence via Database JDBC (Java Database Connectivity) JDBC API Wendy Liu CSC309F Fall 2007 1 2 Java Persistence Persistence via Database JDBC (Java

More information

Programming in Java

Programming in Java 320341 Programming in Java Fall Semester 2014 Lecture 16: Introduction to Database Programming Instructor: Slides: Jürgen Schönwälder Bendick Mahleko Objectives This lecture introduces the following -

More information

CHAPTER 2 JDBC FUNDAMENTALS

CHAPTER 2 JDBC FUNDAMENTALS CHAPTER 2 JDBC FUNDAMENTALS OBJECTIVES After completing JDBC Fundamentals, you will be able to: Know the main classes in the JDBC API, including packages java.sql and javax.sql Know the difference between

More information

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim ERwin and JDBC Mar. 6, 2007 Myoung Ho Kim ERwin ERwin a popular commercial ER modeling tool» other tools: Dia (open source), Visio, ConceptDraw, etc. supports database schema generation 2 ERwin UI 3 Data

More information

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases. JDBC The JDBC TM API is the application programming interface that provides universal data access for the Java TM platform. In other words, the JDBC API is used to work with a relational database or other

More information

access to a JCA connection in WebSphere Application Server

access to a JCA connection in WebSphere Application Server Understanding connection transitions: Avoiding multithreaded access to a JCA connection in WebSphere Application Server Anoop Ramachandra (anramach@in.ibm.com) Senior Staff Software Engineer IBM 09 May

More information

UNIT-3 Java Database Client/Server

UNIT-3 Java Database Client/Server UNIT-3 Java Database Client/Server TOPICS TO BE COVERED 3.1 Client-Server Design: Two-Tier Database Design, Three-Tier Database Design 3.2 The JDBC API: The API Components, Database Creation, table creation

More information

Departamento de Lenguajes y Sistemas Informáticos

Departamento de Lenguajes y Sistemas Informáticos Departamento de Lenguajes y Sistemas Informáticos ! " # $% &'' () * +, ! -. /,#0 &. +, +*,1 $23.*4.5*46.-.2) 7.,8 +*,1 $ 6 +*,1) $23.*4.5 7.-.2) 9 :$java.sql.*),,1 $ ;0,9,1

More information

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Objectives Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity Setting Up JDBC Before you can begin to utilize JDBC, you must

More information

Java E-Commerce Martin Cooke,

Java E-Commerce Martin Cooke, Java E-Commerce Martin Cooke, 2002 1 Java Database Connectivity (JDBC) Plan Java database connectivity API (JDBC) Examples Advanced features JNDI JDBC 13/02/2004 Java E-Commerce Martin Cooke, 2003 2 Design

More information

JDBC [Java DataBase Connectivity]

JDBC [Java DataBase Connectivity] JDBC [Java DataBase Connectivity] Introduction Almost all the web applications need to work with the data stored in the databases. JDBC is Java specification that allows the Java programs to access the

More information

13 Creation and Manipulation of Tables and Databases

13 Creation and Manipulation of Tables and Databases 150.420 Informationslogistik SQL Handout No. 9 SS 2013 13 Creation and Manipulation of Tables and Databases 13.1 Creation and Deletion Databases can be created and deleted using respectively. CREATE DATABASE

More information

Working with Databases and Java

Working with Databases and Java Working with Databases and Java Pedro Contreras Department of Computer Science Royal Holloway, University of London January 30, 2008 Outline Introduction to relational databases Introduction to Structured

More information

Preview from Notesale.co.uk Page 21 of 162

Preview from Notesale.co.uk Page 21 of 162 import java.sql.*; public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp";

More information

What is Transaction? Why Transaction Management Required? JDBC Transaction Management in Java with Example. JDBC Transaction Management Example

What is Transaction? Why Transaction Management Required? JDBC Transaction Management in Java with Example. JDBC Transaction Management Example JDBC Transaction Management in Java with Example Here you will learn to implement JDBC transaction management in java. By default database is in auto commit mode. That means for any insert, update or delete

More information

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL. SQL: Programming CPS 116 Introduction to Database Systems Announcements (September 25) 2 Homework #2 due this Thursday Submit to Yi not through Jun s office door Solution available this weekend No class

More information

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle How to Interact with DataBase? THETOPPERSWAY.COM Generally every DB vendor provides a User Interface through which we can easily execute SQL query s and get the result (For example Oracle Query Manager

More information

CSE 308. Database Issues. Goals. Separate the application code from the database

CSE 308. Database Issues. Goals. Separate the application code from the database CSE 308 Database Issues The following databases are created with password as changeit anticyber cyber cedar dogwood elm clan Goals Separate the application code from the database Encourages you to think

More information

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1.

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1. Lecture 9&10 JDBC Java and SQL Basics Data Manipulation How to do it patterns etc. Transactions Summary JDBC provides A mechanism for to database systems An API for: Managing this Sending s to the DB Receiving

More information

Database Applications (15-415)

Database Applications (15-415) Database Applications (15-415) SQL-Part III & Storing Data: Disks and Files- Part I Lecture 8, February 5, 2014 Mohammad Hammoud Today Last Session: Standard Query Language (SQL)- Part II Today s Session:

More information

Acknowledgments About the Authors

Acknowledgments About the Authors Acknowledgments p. xi About the Authors p. xiii Introduction p. xv An Overview of MySQL p. 1 Why Use an RDBMS? p. 2 Multiuser Access p. 2 Storage Transparency p. 2 Transactions p. 3 Searching, Modifying,

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer About the Tutorial JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac

More information

JDBC Java Database Connectivity is a Java feature that lets you connect

JDBC Java Database Connectivity is a Java feature that lets you connect Chapter 4: Using JDBC to Connect to a Database In This Chapter Configuring JDBC drivers Creating a connection Executing SQL statements Retrieving result data Updating and deleting data JDBC Java Database

More information

Transactions & Concurrency Control

Transactions & Concurrency Control CMPUT 391 Database Management Systems & Concurrency Control - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta Outline Transaction Isolation & Consistency Isolation

More information

DB Programming. Database Systems

DB Programming. Database Systems DB Programming Database Systems 1 Agenda MySQL data types Altering the Schema More Advanced MySQL JDBC DB Coding Tips 2 MySQL Data Types There are 3 main groups of types: Numeric Date String http://dev.mysql.com/doc/refman/5.6/en/data-types.html

More information

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming Lecture 8 1 Outline Context General Approaches Typical Programming Sequence Examples 2 Database Design and Implementation Process Normalization 3 SQL via API Embedded SQL SQLJ General Approaches DB Programming

More information

Why use a database? You can query the data (run searches) You can integrate with other business systems that use the same database You can store huge

Why use a database? You can query the data (run searches) You can integrate with other business systems that use the same database You can store huge 175 Why use a database? You can query the data (run searches) You can integrate with other business systems that use the same database You can store huge numbers of records without the risk of corruption

More information

Java Database Connectivity

Java Database Connectivity Java Database Connectivity Introduction Java Database Connectivity (JDBC) provides a standard library for accessing databases. The JDBC API contains number of interfaces and classes that are extensively

More information

Database Application Development

Database Application Development Database Application Development Chapter 6 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Overview Concepts covered in this lecture: SQL in application code Embedded SQL Cursors Dynamic

More information

SQL in a Server Environment (ii)

SQL in a Server Environment (ii) ICS 321 Spring 2012 SQL in a Server Environment (ii) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 03/19/2012 Lipyeow Lim -- University of Hawaii at Manoa

More information

CSE 135. Three-Tier Architecture. Applications Utilizing Databases. Browser. App. Server. Database. Server

CSE 135. Three-Tier Architecture. Applications Utilizing Databases. Browser. App. Server. Database. Server CSE 135 Applications Utilizing Databases Three-Tier Architecture Located @ Any PC HTTP Requests Browser HTML Located @ Server 2 App Server JDBC Requests JSPs Tuples Located @ Server 1 Database Server 2

More information

Database Application Development Part 2 - Chapter

Database Application Development Part 2 - Chapter Database Application Development Part 2 - Chapter 6.3-6.7 http://xkcd.com/327 -- CC BY-NC 2.5 Randall Munroe Comp 521 Files and Databases Fall 2014 1 Alternative Approach v Abstract Database interface

More information

JDBC MOCK TEST JDBC MOCK TEST IV

JDBC MOCK TEST JDBC MOCK TEST IV http://www.tutorialspoint.com JDBC MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to JDBC Framework. You can download these sample mock tests at your

More information

How to program applications. CS 2550 / Spring 2006 Principles of Database Systems. SQL is not enough. Roadmap

How to program applications. CS 2550 / Spring 2006 Principles of Database Systems. SQL is not enough. Roadmap How to program applications CS 2550 / Spring 2006 Principles of Database Systems 05 SQL Programming Using existing languages: Embed SQL into Host language ESQL, SQLJ Use a library of functions Design a

More information

Database in Applica.on Development. Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Database in Applica.on Development. Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata Database in Applica.on Deelopment Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata SQL from Programs SQL commands can be called from within a host language program C, C++, Jaa, Two

More information

Instructor: Jinze Liu. Fall 2008

Instructor: Jinze Liu. Fall 2008 Instructor: Jinze Liu Fall 2008 Database Project Database Architecture Database programming 2 Goal Design and implement a real application? Jinze Liu @ University of Kentucky 9/16/2008 3 Goal Design and

More information

Web Applications and Database Connectivity using JDBC (Part II)

Web Applications and Database Connectivity using JDBC (Part II) Web Applications and Database Connectivity using JDBC (Part II) Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2007-02-08 ATIJ Web Applications

More information

Chapter 13 Introduction to SQL Programming Techniques

Chapter 13 Introduction to SQL Programming Techniques Chapter 13 Introduction to SQL Programming Techniques Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Outline Database Programming: Techniques and Issues Embedded

More information

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA OUTLINE Postgresql installation Introduction of JDBC Stored Procedure POSTGRES INSTALLATION (1) Extract the source file Start the configuration

More information

SQL Environment: Module Types. System Aspects of SQL. SQL Environment: Introduction. SQL Environment: Introduction. SQL Environment: Privileges

SQL Environment: Module Types. System Aspects of SQL. SQL Environment: Introduction. SQL Environment: Introduction. SQL Environment: Privileges SQL Environment: Module Types System Aspects of SQL Generic SQL Interface: Module: each query or statement Embedded SQL: SQL statements within host-language program SQL statements pre-processed to function

More information

DB I. 1 Dr. Ahmed ElShafee, Java course

DB I. 1 Dr. Ahmed ElShafee, Java course Lecture (15) DB I Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, Java course Agenda 2 Dr. Ahmed ElShafee, Java course Introduction Java uses something called JDBC (Java Database Connectivity) to connect to databases.

More information

Database Application Development

Database Application Development CS 461: Database Systems Database Application Development supplementary material: Database Management Systems Sec. 6.2, 6.3 DBUtils.java, Student.java, Registrar.java, RegistrarServlet.java, PgRegistrar.sql

More information

Java Database Connectivity

Java Database Connectivity Java Database Connectivity ADVANCED FEATURES Dr. Syed Imtiyaz Hassan Assistant Professor, Deptt. of CSE, Jamia Hamdard (Deemed to be University), New Delhi, India. s.imtiyaz@jamiahamdard.ac.in Agenda Scrollable

More information

Introduction to SQL & Database Application Development Using Java

Introduction to SQL & Database Application Development Using Java Introduction to SQL & Database Application Development Using Java By Alan Andrea The purpose of this paper is to give an introduction to relational database design and sql with a follow up on how these

More information