Accessing Databases with JDBC. Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes.

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
JDBC1 JDBC Introduction JDBC provides a standard library for accessing relational databases –API standardizes Way to establish.
Objectives Describe JDBC Describe JDBC Driver Types
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.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
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.
Java: JDBC INE2720 Web Application Software Development Essential Materials.
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.
JDBC1 Course Material Usage Rules PowerPoint slides for use only in for-credit courses at degree-granting institutions –Slides not.
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.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
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.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
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.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
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.
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.
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.
Basics of JDBC Session 14.
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.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
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
CS3220 Web and Internet Programming Database Access with JDBC
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.
Interacting with Database
JDBC Database Management Database connectivity
JDBC – Java Database Connectivity
Web Technologies IT230 Dr Mohamed Habib.
CS320 Web and Internet Programming Database Access with JDBC
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:

Accessing Databases with JDBC

Introduction to JDBC JDBC provides a standard library for accessing databases by using the JDBC API. JDBC standardizes the approach for connecting databases. The approach for sending queries and committing transactions and the data structure representing the result. It does not attempt to standardize the SQL Syntax.

Introduction to JDBC Using JDBC lets you change database hosts, ports, and even database vendors with minimal changes to your code. Officially JDBC does not stand for anything. But “JAVA Database Connectivity” is commonly used as the long form of the name.

Topics to be Covered Using JDBC in General Basic JDBC Using prepared statements Creating Callable Statements Using Database Transactions

Using JDBC in General 1.Load the JDBC Driver. 2.Define the connection URL. 3.Establish the connection. 4.Create a Statement Object 5.Execute a query or update. 6.Process the results. 7.Close the connection.

Load the JDBC Driver. To load a driver you must specify the classname of the database driver in the class.forName method. By doing so, you automatically create a driver instance and register it with the JDBC manager.

Define the connection URL. In JDBC, a connection URL specifies the server, host port and database name with which to establish a connection.

Establish the connection. 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.

Create a Statement Object Creating a statement object enables you to send queries and commands to the database.

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.

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 get.xxx methods.

Close the connection. When you are finished performing queries and processing results, you should close the connection, releasing resources to the database.

Loading the Driver

Load the JDBC Driver The driver is the piece of software tat knows how to talk to the actual database server. One of the advantages of the JDBC approach is that the database server requires no changes whatsoever. Instead, the JDB driver (on the client) translates calls written in the Java programming language into the native format required by the server.

Loading the JDBC Driver try{ class.forName("connect.microsoft.MicrosoftDriver"); class.forName("oracle.jdbc.driver.OracleDriver"); class.forName("com.sybase.jdbc.SybDriver"); }catch(classNotFoundException cnfe){ System.err.println("Ërror loading driver: " + cnfe); }

Class.forName This method takes a string representing a fully qualified class name (i.e, one that includes package names) and loads the corresponding class. This could throw a ClassNotFoundException, so it should be inside a try catch block.

Load the JDBC Driver This approach means that you have to obtain a JDBC driver specific to the database that you are using and you will need to check the vendor’s documentation for the fully qualified class name to use.

Defining the Connection URL Once you have loaded the JDBC driver, you must specify the location of the database server. URLs referring to databases use the “jdbc:” protocol and embed the server host, port and database name within the URL. The exact format is defined in the documentation that comes with the particular driver.

Define the Connection URL String host = “dbhost.yourcompany.com” String dbName = “someName”; Int port = 1234; String OracleURL = + host + “:” + port + “:” + dbName; String SybaseURL = “jdbc:sybase:Tds” + host + “:” + port + “:” + “?SERVICENAME=” + dbName; String msAccessURL = “jdbc:odbc:” + dbName;

Establish the Connection To make the actual network connection, pass the URL, database user name and password to the getConnection method of the DriverManager class. Note that getConnection throws an SQLException, so you need to use a try/catch block.

Establish the Connection String username = “jay_debesee”; String password = “secret”; Connection connection = DriverManager.getConnection(oracleURL, username password);

Establish the connection The connection class includes other useful methods. –prepareStatement. – creates precompiled queries for submission to the database. –prepareCall – accesses stored procedures in the database. –rollback/commit – controls transaction management. –Close – terminates the open connection. –isClosed – determines whether the connection timed out or was explicitly closed.

Establish the connection An optional part of establishin the connection is to look up information about the database with the getMetaData method. This method returns a DatabaseMetaData object that has methods which you can discover the name and version of the database.

Establish the connection DatabaseMetaData dbMetaData = connection.getMetaData(); String productName = dbMetaData.getDatabaseProductName(); System.out.println(“Database: ” + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); System.out.println(“Version: ” + productVersion);

Create a Statement Object A create statement object is used to send queries and commands to the database. It is created from the connection using the CreateStatement. Most but not all, database drivers permit multiple concurrent Statement objects to be open on the same connection. Statement statement = connection.CreateStatement();

Execute a Query or Update Once you have 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);

Execute a Query or Update 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. Returns the number of rows affected, which could be zero. Also provides support for DDL commands such as (CREATE, DROP, ALTER)

Execute a Query or Update executeBatch – executes a group of commands as a unit, returning an array with the update counts for each command. Use addBatch to add a command to the batch group. Note that vendors are not required to implement this method in their driver to the JDBC.

Execute a Query or Update setQueryTimeout – specifies the amount of time a driver waits for the result before throwing an SQLException. getMaxRows/setMaxRows – determines the number of rows a ResultSet may contain. Excess rows are silently dropped. The default is zero for no limit.

Execute a Query or Update In addition to using the methods described here to send arbitrary commands, you can use a Statement object to create parameterized queries by which values are supplied to a precompiled fixed-format query.

Process the results The simplest way to handle results is to use the next method of ResultSet to move through thetable row at a time. Within a row, 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.

Process the results Here is an example that prints the values of the first two columns and the first name and last name, for all rows of a result set. While(resultSet.next()){ System.out.println(resultSet.getString(1) + “ ” + resultSet.getString(2) + “ ”+ resultSet.getString(“firstname”) + “ ” resultSet.GetString(“lastname”)); }

Process the results The following list summarizes useful ResultSet methods. –Next/previous. Moves the cursor to the next or previous row in the result set –Relative/absolute. The relative method moves the cursor a relative number of rows, either positive or negative. The absolute methods 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.

Process the results –getXXX – returns the value from the column specified by the column name or column index as an xxx JavaType. Can return 0 or null if the value is an SQL null. –wasNull – checks checks whether the last getXXX was read as an SQL NULL. This check is important if the column type is a primitive and the vlue in the database is 0. A zero value would be indistinguishable from a database value of NULL. –findColumn – returns the index in the ResultSet corresponding to the specified column name.

Process the results –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.

Process the results The getMetaData method is particularly useful. Given only a ResultSet, you have to know the name, number and type of the columns to be able to process the table properly. For ad hoc queries, it is useful to be able to dynamically discover high-level information about the result.

ResultSetMetaData –getColumnCount – returns the number of columns in the ResultSet. –getColumnName – returns the database name of a column –getColumnType – returns the SQL type to compare with entries in java.sql.Types –isReadOnly. Indicates whether the entry is a read- only value. –isSearchable – indicates whether the column can be used in a WHERE clause. –isNullable – indicates whether storing a null is legal for the column.

Close the connection To close the connection explicitly, you input Connection.Close(); Closing the connection also closes the corresponding statement and result set objects.