COP 4610L: Applications in the Enterprise Spring 2005

Slides:



Advertisements
Similar presentations
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Advertisements

JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
 Pearson Education, Inc. All rights reserved Accessing Databases with JDBC.
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.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Database applications with JDBC Jiafan Zhou. DBMS Database management systems (DBMS) is an organised collection of data. Usually database stores data.
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.
Introduction to JDBC Pertemuan 10 Matakuliah: Web Programming Tahun: 2009.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
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.
Javax.sql and java.sql. java.sql Interface Connection public interface Connection extends WrapperWrapper A connection (session) with a specific database.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
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.
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.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
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.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
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™ Advanced Concepts
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC (Java Database Connectivity)
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
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.
Chapter 7 Chapter 7 Java Database Connectivity using JSP 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC.
Chapter 38 Advanced Java Database Programming
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
Lec - 14.
Java swings.
JDBC – Java Database Connectivity
Chapter 41 Advanced Java Database Programming
CS320 Web and Internet Programming Database Access with JDBC
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Objectives In this lesson, you will learn about:
Interacting with Database
Super Market Management
Bolat Azamat, Kim Dongmin
COP 4610L: Applications in the Enterprise Spring 2005
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

COP 4610L: Applications in the Enterprise Spring 2005 Introduction to JDBC – Part 2 Instructor : Mark Llewellyn markl@cs.ucf.edu CSB 242, 823-2790 http://www.cs.ucf.edu/courses/cop4610L/spr2005 Phd, MS, Under School of Electrical Engineering and Computer Science University of Central Florida

The PreparedStatement Interface In the previous set of notes, once we established a connection to a particular database, it was used to send an SQL statement from the application to the database. The Statement interface is used to execute static SQL statements that contain no parameters. The PreparedStatement interface, which extends the Statement interface, is used to execute a precompiled SQL statement with or without IN parameters. Since the SQL statements are precompiled, they are extremely efficient for repeated execution.

The PreparedStatement Interface (cont.) A PreparedStatement object is created using the preparedStatement method in the Connection interface. Statement pstmt = connection.preparedStatement (“insert into bikes (bikename, size, color, cost, purchased, mileage) + values ( ?, ?, ?, ?, ?, ?)” ); Placeholders for the values that will be dynamically provided by the user.

The PreparedStatement Interface (cont.) As a subinterface 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 signature: setX (int parameterIndex, X value); where X is the type of parameter and parameterIndex is the index of the parameter in the statement.

The PreparedStatement Interface (cont.) As an example, the method setString( int parameterIndex, String value) sets a String value to the specified parameter. Once the parameters are set, the prepared statement is executed like any other SQL statement where executeQuery() is used for SELECT statements and executeUpdate() is used for DDL or update commands. These two methods are similar to those found in the Statement interface except that they have no parameters since the SQL statements are already specified in the preparedStatement method when the object of a PreparedStatement is created.

FindBikeUsingPreparedStatement import javax.swing.*; import java.sql.*; import java.awt.*; import java.awt.event.*; public class FindBikeUsingPreparedStatement extends JApplet { boolean isStandalone = false; private JTextField jtfbike = new JTextField(25); private JTextField jtfcost = new JTextField(6); private JButton jbtShowCost = new JButton("Show Bike Cost Info"); // PreparedStatement for executing queries private PreparedStatement pstmt; /** Initialize the applet */ public void init() { // Initialize database connection and create a PreparedStatement object initializeDB(); jbtShowCost.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jbtShowCost_actionPerformed(e); } }); PreparedStatement object

JPanel jPanel1 = new JPanel(); jPanel1 JPanel jPanel1 = new JPanel(); jPanel1.add(new JLabel("Bike Name")); jPanel1.add(jtfbike); jPanel1.add(jbtShowCost); this.getContentPane().add(jPanel1, BorderLayout.NORTH); } private void initializeDB() { try { // Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded"); // Establish a connection Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/bikedb", "root", "root"); System.out.println("Database connected"); String queryString = "select cost from bikes where bikename = ?"; // Create a statement pstmt = connection.prepareStatement(queryString); } catch (Exception ex) { ex.printStackTrace(); } } queryString contains the SQL statement with the ? Placeholder for the value to be determined at run-time. Invoke the preparedStatement() method on the connection.

Set first parameter value for PreparedStatement object private void jbtShowCost_actionPerformed(ActionEvent e) { String bikename = jtfbike.getText(); String cost = jtfcost.getText(); try { pstmt.setString(1, bikename); ResultSet rset = pstmt.executeQuery(); if (rset.next()) { String price = rset.getString(1); // Display result in a dialog box JOptionPane.showMessageDialog(null, bikename + " cost $" + price); } else { // Display result in a dialog box JOptionPane.showMessageDialog(null, "Bike Not Found"); } } catch (SQLException ex) { ex.printStackTrace(); } } Set first parameter value for PreparedStatement object Execute query using PreparedStatement object Get data from results set returned by JDBC. /** Main method */ public static void main(String[] args) { FindBikeUsingPreparedStatement applet = new FindBikeUsingPreparedStatement(); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Find Bike Cost"); frame.getContentPane().add(applet, BorderLayout.CENTER); applet.init(); applet.start(); frame.setSize(580, 80); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); frame.setVisible(true); } }

Output from FindBikeUsingPreparedStatement

The RowSet Interface (cont.) Interface RowSet provides several set methods that allow the programmer to specify the properties needed to establish a connection (such as the database URL, user name, password, etc.) and a create a Statement (such as a query). Interface RowSet also provides several get methods that return these properties. More information on these methods can be found at: http://java.sun.com/j2se/1.5.0/docs/api/javax/sql/RowSet.html

The RowSet Interface (cont.) RowSet is part of the javax.sql package. Although part of the Java 2 Standard Edition, the classes and interfaces of package javax.sql are most often used in the context of the Java 2 Platform Enterprise Edition (J2EE). We may get to some J2EE development later in the semester. You can learn more about J2EE at www.java.sun.com/j2ee.

Using the RowSet Interface There are two types of RowSet objects – connected and disconnected. A connected RowSet object connects to the database once and remains connected until the application terminates. A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closed the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated to the database after a disconnected RowSet reestablishes the connection with the database.

Using the RowSet Interface (cont.) J2SE 5.0 package javax.sql.rowset contains two subinterfaces of RowSet – JdbcRowSet and CachedRowSet. JdbcRowSet, a connected RowSet, acts as a wrapper around a ResultSet object, and allows programmers to scroll through and update the rows in the ResultSet object. Recall that by default, a ResultSet object is non-scrollable and read only – you must explicitly set the result-set type constant to TYPE_SCROLL_INSENSITIVE and set the result set concurrency constant to CONCUR_UPDATEABLE to make a ResultSet object scrollable and updatable.

Using the RowSet Interface (cont.) A JdbcRowSet object is scrollable and updatable by default. CachedRowSet, a disconnected RowSet, caches the data of a ResultSet in memory and disconnects from the database. Like JdbcRowSet, a CachedRowSet object is scrollable and updatable by default. A CachedRowSet is also serializable, so it can be passed between Java applications through a network. However, a CachedRowSet has a limitation – the amount of data that can be stored in memory is limited. There are three other subinterfaces in this package (FilteredRowSet, WebRowSet, and JoinRowSet).

Using the RowSet Interface (cont.) The code example on the next couple of pages illustrates the use of the RowSet interface. Notice that unlike the TableSet version in the previous set of notes, the connection is made and the query executed automatically.

Class: JdbcRowSetTest – page 1 // Displaying the contents of the bikes table using JdbcRowSet. import java.sql.ResultSetMetaData; import java.sql.SQLException; import javax.sql.rowset.JdbcRowSet; import com.sun.rowset.JdbcRowSetImpl; // Sun’s JdbcRowSet implementation public class JdbcRowSetTest { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DATABASE_URL = "jdbc:mysql://localhost/bikedb"; static final String USERNAME = "root"; static final String PASSWORD = “root"; // constructor connects to database, queries database, processes // results and displays results in window public JdbcRowSetTest() { // connect to database books and query database try { Class.forName( JDBC_DRIVER ); // load database driver class

Class: JdbcRowSetTest – page 2 // specify properties of JdbcRowSet JdbcRowSet rowSet = new JdbcRowSetImpl(); rowSet.setUrl( DATABASE_URL ); // set database URL rowSet.setUsername( USERNAME ); // set username rowSet.setPassword( PASSWORD ); // set password //set query rowSet.setCommand( "SELECT bikename,size,purchased,cost FROM bikes” ); rowSet.execute(); // execute query // process query results ResultSetMetaData metaData = rowSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); System.out.println( "Bikes Table of bikedb Database:" ); // display rowset header for ( int i = 1; i <= numberOfColumns; i++ ) System.out.printf( "%-12s\t", metaData.getColumnName( i ) ); System.out.println(); SQL command to be executed.

Class: JdbcRowSetTest – page 3 // display each row while ( rowSet.next() ) { for ( int i = 1; i <= numberOfColumns; i++ ) System.out.printf( "%-12s\t", rowSet.getObject( i ) ); System.out.println(); } // end while } // end try catch ( SQLException sqlException ) { sqlException.printStackTrace(); System.exit( 1 ); } // end catch catch ( ClassNotFoundException classNotFound ) { classNotFound.printStackTrace(); System.exit( 1 ); } // end catch } // end DisplayBikes constructor // launch the application public static void main( String args[] ) { { JdbcRowSetTest window = new JdbcRowSetTest(); } // end main } // end class JdbcRowSetTest

Execution of JdbcRowSetTest Display of default query results from JdbcRowSetTest application