Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.

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.
CSC 2720 Building Web Applications JDBC. JDBC Introduction  Java Database Connectivity (JDBC) is an API that enables Java developers to access any tabular.
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.
Objectives Describe JDBC Describe JDBC Driver Types
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.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Think Possibility Integrating Web Applications With Databases.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
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.
What is JDBC? Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. provides.
Database Programming in Java Corresponds with Chapter 32, 33.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
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.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
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.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
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.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
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 Session 14.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_Oracle10g_JDBC 1 Application Development (JDBC)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
DEPTT. OF COMP. SC & APPLICATIONS
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
JDBC Database Management Database connectivity
JDBC – Java Database Connectivity
Web Technologies IT230 Dr Mohamed Habib.
Introduction to Programming with Java
Chapter 16 JAVA DATABASE CONNECTIVITY
Interacting with Database
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Chapter 17 Accessing Databases with JDBC

JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access a wide variety of SQL databases with exactly the same Java syntax. JDBC does not attempt to standardize the SQL syntax. So, you can use any SQL extensions your database vendor supports

JDBC JDBC is not an acronym and thus does not stand for anything. Unofficially, "Java DataBase Connectivity" is commonly used as the long form of the name.

Using JDBC in General: 7 steps 1) Load the JDBC driver: classname of the database driver in the Class.forName method. 2) Define the connection URL : specifies the server host, port, and database name with which to establish a connection. 3) Establish the connection :

Using JDBC With the connection URL, username, and password, a network connection to the database can be established. Once the connection is established, database queries can be performed until the connection is closed. 4) Create a Statement object : enables to send queries and commands to the database.

Using JDBC 5) Execute a query or update : Given a Statement object, you can send SQL statements to the database by using the execute, executeQuery, executeUpdate, or executeBatch methods 6) Process the results : When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows and columns that you can process by calls to next and various getXxx methods. 7)Close the connection

Using JDBC Step 1) Load the JDBC Driver The driver is the piece of software that knows how to talk to the actual database server To load the driver, load the appropriate class; a static block in the driver class itself automatically makes a driver instance and registers it with the JDBC driver manager.

Load JDBC the Driver The method takes a string representing a fully qualified classname and loads the corresponding class. This call could throw a ClassNotFoundException, so it should be inside a try/catch block as shown below:

Load JDBC the Driver try { Class.forName("connect.microsoft.Micro softDriver"); Class.forName("oracle.jdbc.driver.Oracl eDriver"); Class.forName("com.sybase.jdbc.SybDri ver"); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); }

Define the Connection URL specify the location of the database server. URLs referring to databases use the jdbc: protocol and embed the server host, port, and database name (or reference) within the URL. String host = "dbhost.yourcompany.com"; String dbName = "someName"; String msAccessURL = "jdbc:odbc:" + dbName;

Establish the Connection To make the actual network connection, pass the URL, database username, and database password to the getConnection method of the DriverManager class getConnection throws an SQLException use a try/catch block.

Methods in The Connection class prepareStatement. Creates precompiled queries for submission to the database. prepareCall. Accesses stored procedures in the database. For details rollback/commit close isClosed

Create a Statement Object A Statement object is used to send queries and commands to the database. It is created from the Connection using createStatement as follows. Statement statement = connection.createStatement();

Execute a Query or Update Once having a Statement object, you can use it to send SQL queries by using the executeQuery method, which returns an object of type ResultSet String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query);

Methods in Statement Class executeQuery. Executes an SQL query and returns the data in a ResultSet. The ResultSet may be empty, but never null. executeUpdate. Used for UPDATE, INSERT, or DELETE commands. executeBatch. Executes a group of commands as a unit, returning an array with the update counts for each command setQueryTimeout. Specifies the amount of time a driver waits for the result before throwing an SQLException. getMaxRows/setMaxRows. etermines the number of rows a ResultSet may contain

Process the Results The simplest way to handle the results is to use the next method of ResultSet to move through the table a row at a time ResultSet provides various getXxx methods that take a column name or column index as an argument and return the result in a variety of different Java types use getInt if the value should be an integer, getString for a String

ResultSet methods next/previous relative/absolute. The relative method moves the cursor a relative number of rows, either positive (up) or negative (down). The absolute method moves the cursor to the given row number. If the absolute value is negative, the cursor is positioned relative to the end of the ResultSet

ResultSet methods getXxx. Returns the value from the column specified by the column name or column index as an Xxx Java type (see java.sql.Types). Can return 0 or null if the value is an SQL NULL wasNull. Checks whether the last getXxx read was an SQL NULL.

ResultSet methods findColumn. Returns the index in the ResultSet corresponding to the specified column name. getRow. Returns the current row number, with the first row starting at 1 getMetaData. Returns a ResultSetMetaData object describing the ResultSet. ResultSetMetaData gives the number of columns and the column names

ResultSet methods The getMetaData method is particularly useful role of the ResultSetMetaData class: it lets you determine the number, names, and types of the columns in the ResultSet

Mothods in ResultSetMetaData getColumnCount: Returns the number of columns in the ResultSet getColumnName: Returns the database name of a column getColumnType: Returns the SQL type isReadOnly isSearchable: Indicates whether the column can be used in a WHERE clause. isNullable: Indicates whether storing NULL is legal for the column

Close the Connection connection.close(); Closing the connection also closes the corresponding Statement and ResultSet objects.

JDBC Examples Microsoft Access Northwind database To configure the Northwind database for access from JDBC, section 18.1 Listing 17.1, presents a standalone class called NorthwindTest that follows the seven steps outlined in the previous section to display the results of querying the Employee table. Listing 17.1

JDBC Examples (Cont) The results for the NorthwindTest are shown in Listing 17.2Listing 17.2 Since NorthwindTest is in the coreservlets package, it resides in a subdirectory called coreservlets. Before compiling the file, set the CLASSPATH to include the directory containing the coreservlets directory.

JDBC Examples (Cont) Second example NorthwindServlet (Listing 17.3), the information for performing the query is taken from an HTML form, NorthwindForm.html, shown in Listing 17.4.Listing 17.3Listing 17.4 You can enter the query into the form text area before submitting the form to the servlet. The servlet also demonstrates the use of DatabaseMetaData to look up the product name and product version of the database

Simplifying Database Access with JDBC Utilities The DriverUtilities class (Listing 17.5) simplifies the building of a URL to connect to a database.Listing 17.5 As another example, the ConnectionInfoBean class (Listing 17.9) provides a utility method, getConnection, for obtaining a Connection to a database.Listing 17.9

Simplifying Database Access with JDBC Utilities (Cont) Four utility classes DriverUtilities DriverUtilities2 DriverInfoBean ConnectionInfoBean

Using Prepared Statements To execute similar SQL statements multiple times, using parameterized (or "prepared") statements The idea is to create a parameterized statement in a standard form that is sent to the database for compilation before actually being used

Using Prepared Statements (Cont) Use a question mark to indicate the places where a value will be substituted into the statement. Each time you use the prepared statement, you simply replace the marked parameters, using a setXxx call corresponding to the entry you want to set (using 1-based indexing) and the type of the parameter (e.g., setInt, setString). Then use executeQuery (if you want a ResultSet back) or execute/executeUpdate to modify table data. Listing PreparedStatements.java

Creating Callable Statements With a CallableStatement, you can execute a stored procedure or function in a database For example, in an Oracle database, you can write a procedure or function in PL/SQL and store it in the database along with the tables. Then, you can create a connection to the database and execute the stored procedure or function through a CallableStatement.

Creating Callable Statements A stored procedure’s advantages. Syntax errors are caught at compile time instead of at runtime. The database procedure may run much faster than a regular SQL query; The programmer only needs to know about the input and output parameters, not the table structure. Coding of the stored procedure may be simpler in the database language than in the Java programming language.

Creating Callable Statements Disadvantage: First: need to learn a new database-specific language. Second: the business logic of the stored procedure executes on the database server instead of on the client machine or Web server Calling a stored procedure in a database involves the six basic steps outlined below and then described in detail in the following subsections

Creating Callable Statements Define the call to the database procedure Prepare a CallableStatement for the procedure Register the output parameter types Provide values for the input parameters Execute the stored procedure Access the returned output parameters

Creating Callable Statements Define the Call to the Database Procedure Procedure with no parameters. { call procedure_name } Procedure with input parameters. { call procedure_name(?, ?,...) } Procedure with an output parameter. { ? call procedure_name } Procedure with input and output parameters. { ? = call procedure_name(?, ?,...) }

Prepare a CallableStatement for the Procedure String procedure = "{ ? = call procedure_name( ?, ? ) }"; CallableStatement statement = connection.prepareCall(procedure);

Register the Output Parameter Types You must register the JDBC type of each output parameter, using registerOutParameter, as follows, statement.registerOutParameter(n, type); where n corresponds to the ordered output parameter (using 1-based indexing), type corresponds to a constant defined in the java.sql.Types class (Types.FLOAT, Types.DATE, etc.).

Provide Values for the Input Parameters statement.setString(2, "name"); statement.setFloat(3, 26.0F); Execute the Stored Procedure statement.execute(); Access the Output Parameters int value = statement.getInt(1); Example Listing and 17.12

Transaction Definition When a database is updated, but behavior can be programmatically turned off. -> problem occurs with the updates If the updates execute successfully, then the changes can later be permanently committed to the database Listing Transactions.java