UNIT-2 Java Database Programming

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 32 Java Database.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 37 Java Database Programming.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 37 Java Database Programming.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Accessing Databases with JDBC. Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Database Programming in Java Corresponds with Chapter 32, 33.
Announcements Read JDBC Project Step 5, due Monday.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
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.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 33 Advanced Java.
JDBC – Java Database Concentricity
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
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.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
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.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
Web Programming MySql JDBC Web Programming.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Basics of JDBC Session 14.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
JDBC.
Chapter 38 Advanced Java Database Programming
DEPTT. OF COMP. SC & APPLICATIONS
CS3220 Web and Internet Programming Database Access with JDBC
JDBC 15-Apr-18.
JDBC Database Management Database connectivity
JDBC – Java Database Connectivity
Web Technologies IT230 Dr Mohamed Habib.
Chapter 34 Java Database Programming
Chapter 41 Advanced Java Database Programming
JDBC 21-Aug-18.
JDBC.
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

UNIT-2 Java Database Programming Programming in Java UNIT-2 Java Database Programming Lovely Professional University, Punjab

Lovely Professional University, Punjab

JDBC It is Java API for developing Java database applications is called JDBC. JDBC provides Java programmers with a uniform interface for accessing and manipulating a wide range of relational databases. Lovely Professional University, Punjab

JDBC Drivers Types JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4. Lovely Professional University, Punjab

JDBC Driver Types JDBC-ODBC Bridge, plus ODBC driver (Type 1) JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native methods -> Native methods API Native-API, partly Java driver (Type 2) JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library) JDBC-Network driver (Type 3) JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methods Pure Java driver (Type 4) Java methods -> Native methods in Java

Developing Database Applications Using JDBC The JDBC API is a Java application program interface to generic SQL databases that enables Java developers to develop DBMS-independent Java applications using a uniform interface. The JDBC API consists of classes and interfaces for establishing connections with databases, sending SQL statements to databases, processing the results of the SQL statements, and obtaining database metadata. Lovely Professional University, Punjab

Steps during Execution The following steps are executed when running a JDBC application Import the necessary classes Load the JDBC driver Identify the database source Allocate a “connection” object (create) Allocate a “Statement” object (create) Execute a query using the “Statement” object Retrieve data from the returned “ResultSet” object Close the “ResultSet” object Close the “Statement” object Close the “Connection” object

JDBC Component Interaction Driver Manager Creates Creates Creates Connection Statement ResultSet SQL Driver Establish Link to DB Result (tuples) Database

Lovely Professional University, Punjab

Loading drivers An appropriate driver must be loaded using the statement shown below before connecting to a database. Class.forName("JDBCDriverClass"); Lovely Professional University, Punjab

Loading drivers Download mysqljdbc.jar from //www.javatpoint.com/example-to-connect-to-the-mysql-database Copy this jar file into ext folder of jre in java And set path Other jar files can be found from link given in Your Text book “Introduction to Programming ” by Daniel Liang[Page No.1276, Chapter 37]. Lovely Professional University, Punjab

Setting path For temporary setting C:>set classpath C:\Program Files\Java\jre7\lib\ext\mysql-connector-java-5.0.8.-bin.jar;.; For permanent setting Set environment variable in advanced settings of computer Variable name=classpath and value=C:\Program Files\Java\jre7\lib\ext\mysql-connector-java- 5.0.8-bin.jar;.; Lovely Professional University, Punjab

Establishing connections. Connection =DriverManager.getConnection(databaseURL); Connection = DriverManager.getConnection("jdbc:mysql://localhost/javabook", “root", "tiger"); Lovely Professional University, Punjab

Commonly used methods of Connection interface 1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries. 2) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true. 4) public void commit(): saves the changes made since the previous commit/rollback permanent. 5) public void rollback(): Drops all changes made since the previous commit/rollback. 6) public void close(): closes the connection and Releases a JDBC resources immediately. Lovely Professional University, Punjab

Creating statements Statement = connection.createStatement(); Executing statements statement.executeUpdate ("create table Temp (col1 char(5), col2 char(5))"); ResultSet resultSet = statement.executeQuery("select firstName, mi, lastName from Student where lastName = 'Smith'"); Lovely Professional University, Punjab

Commonly used methods of Statement interface The important methods of Statement interface are as follows: 1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. 3) public boolean execute(String sql): is used to execute queries that may return multiple results. 4) public int[] executeBatch(): is used to execute batch of commands. Lovely Professional University, Punjab

Processing ResultSet while (resultSet.next()) System.out.println(resultSet.getString(1) + " " +resultSet.getString(2) + ". " + resultSet.getString(3)); Lovely Professional University, Punjab

ResultSet Methods public boolean first() throws SQLException Moves the cursor to the first row. public void last() throws SQLException Moves the cursor to the last row. public boolean previous() throws SQLException Moves the cursor to the previous row. This method returns false if the previous row is off the result set. public boolean next() throws SQLException Moves the cursor to the next row. This method returns false if there are no more rows in the result set. Lovely Professional University, Punjab

Viewing a Result Set The ResultSet interface contains dozens of methods for getting the data of the current row. There is a get method for each of the possible data types, and each get method has two versions − One that takes in a column name. One that takes in a column index. For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet − Lovely Professional University, Punjab

Methods general form public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName. public int getInt(int columnIndex) throws SQLException Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on. Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL. Lovely Professional University, Punjab

PreparedStatement Most relational databases handles a JDBC / SQL query in four steps: Parse the incoming SQL query Compile the SQL query Plan/optimize the data acquisition path Execute the optimized query / acquire and return data A Statement will always proceed through the four steps above for each SQL query sent to the database. A Prepared Statement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a Prepared Statement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time. Lovely Professional University, Punjab

PreparedStatement The PreparedStatement interface, extending Statement, is used to execute a precompiled SQL statement with or without parameters. Since the SQL statements are precompiled, they are efficient for repeated executions. A PreparedStatement object is created using the prepareStatement method in the Connection interface. For example, the following code creates a PreparedStatement preparedStatement on a particular Connection connection for an SQL insert statement: Statement preparedStatement = connection.prepareStatement("insert into Student (firstName, mi, lastName) " +"values (?, ?, ?)"); Lovely Professional University, Punjab

PreparedStatement As a sub interface of Statement, the PreparedStatement interface inherits all the methods defined in Statement. It also provides the methods for setting parameters in the object of PreparedStatement. These methods are used to set the values for the parameters before executing statements or procedures. In general, the set methods have the following name and signature: setX(intparameterIndex,Xvalue); Where X is the type of the parameter, and parameter Index is the index of the parameter in the statement. The index starts from 1. The following statements pass the parameters “Jack”, “A”, and “Ryan” to the placeholders for firstName, mi, and lastName in PreparedStatement : preparedStatement.setString(1,"Jack"); preparedStatement.setString(2,"A"); preparedStatement.setString(3,"Ryan"); Lovely Professional University, Punjab

PreparedStatement The executeQuery() and executeUpdate()methods are similar to the ones defined in the Statement interface except that they have no parameters, because the SQL statements are already specified in the preparedStatement method when the object of PreparedStatement is created. Lovely Professional University, Punjab

Demo Programs SimpleJdbc.java(Demo Program) FindGrade1.java(Demo Program) FindGradeUsingPreparedStatements.java(Demo Program) Lovely Professional University, Punjab

Retrieving Metadata JDBC provides the DatabaseMetaData interface for obtaining database wide information and the ResultSetMetaData interface for obtaining information on the specific ResultSet, such as column count and column names. Lovely Professional University, Punjab

Database Metadata The Connection interface establishes a connection to a database. It is within the context of a connection that SQL statements are executed and results are returned. A connection also provides access to database metadata information that describes the capabilities of the database, supported SQL grammar, stored procedures, and so on. To obtain an instance of Database- MetaData for a database, use the getMetaData method on a connection object like this: DatabaseMetaData dbMetaData = connection.getMetaData(); TestDatabaseMetaData.java[Demo Program] Lovely Professional University, Punjab

Result Set Metadata A ResultSetMetaData object can be used to find the types and properties of the columns in a ResultSet. To obtain an instance of ResultSetMetaData, use the getMetaData method on a result set like this: ResultSetMetaData rsMetaData = resultSet.getMetaData(); You can use the getColumnCount() method to find the number of columns in the result and the getColumnName(int) method to get the column names. Lovely Professional University, Punjab

Result Set Metadata String getColumnName(int column) Get the designated column's name int getColumnCount() Returns the number of columns in this ResultSet object. boolean isReadOnly(int column) Indicates whether the designated column is definitely not writable. boolean isSearchable(int column) Indicates whether the designated column can be used in a where clause. String getTableName(int column) Gets the designated column's table name. TestResultSetMetaData.java[Demo Program] Lovely Professional University, Punjab

Batch Processing Statement = connection.createStatement(); // Add SQL commands to the batch statement.addBatch("create table T (C1 integer, C2 varchar(15))"); statement.addBatch("insert into T values (100, 'Smith')"); statement.addBatch("insert into T values (200, 'Jones')"); // Execute the batch int count[] = statement.executeBatch(); NOTE:To find out whether a driver supports batch updates, invoke supportsBatchUpdates() on a DatabaseMetaData instance. TestBatchProcessing.java[Demo Programs] Lovely Professional University, Punjab

Why to setAutoCommit to false If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion. That may be fine for simple applications, but there are three reasons why you may want to turn off auto-commit and manage your own transactions: To increase performance To maintain the integrity of business processes Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails. To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again. For example, if you have a Connection object named conn, code the following to turn off auto- commit: conn.setAutoCommit(false); Lovely Professional University, Punjab

Commit & Rollback try{ //Assume a valid connection object conn conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = "INSERT INTO Employees " + "VALUES (106, 20, ‘Roshan', ‘Srivastava')"; stmt.executeUpdate(SQL); //Submit a malformed SQL statement that breaks String SQL = "INSERTED IN Employees " + "VALUES (107, 22, 'Saurabh', 'Sharma')"; // If there is no error. conn.commit(); }catch(SQLException se){ // If there is any error. conn.rollback(); } Lovely Professional University, Punjab