This lecture. Databases - JDBC I. Application Programs. Database Access End Users

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

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

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

Java Database Connectivity (JDBC) 25.1 What is JDBC?

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

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Accessing databases in Java using JDBC

UNIT-3 Java Database Client/Server

Server-side Web Programming

Servlet 5.1 JDBC 5.2 JDBC

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

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

UNIT III - JDBC Two Marks

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

Java Database Connectivity

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

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

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

Working with Databases and Java

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

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

JAVA AND DATABASES. Summer 2018

Chapter 16: Databases

Lab # 9. Java to Database Connection

JDBC, Transactions. Niklas Fors JDBC 1 / 38

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

Student Number: Please fill out the identification section above as well as the one on the back page, and read the instructions below. Good Luck!

COMP102: Introduction to Databases, 23

SQL and Java. Database Systems Lecture 20 Natasha Alechina

SQL DML and DB Applications, JDBC

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

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

Databases SQL IV. (GF Royle, N Spadaccini ) SQL IV 1 / 25

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

SQL in a Server Environment

Programming in Java

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

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

Application Programming for Relational Databases

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

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

JDBC Programming: Intro

This lecture. PHP tags

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

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

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24

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

JDBC 3.0. Java Database Connectivity. 1 Java

SNS COLLEGE OF ENGINEERING, Coimbatore

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

Introduction to SQL & Database Application Development Using Java

SQream Connector JDBC SQream Technologies Version 2.9.3

JDBC [Java DataBase Connectivity]

Databases and MySQL. COMP 342: Programming Methods. 16 September Databases and MySQL

Non-interactive SQL. EECS Introduction to Database Management Systems

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

Databases 2012 Embedded SQL

13 Creation and Manipulation of Tables and Databases

JDBC - INTERVIEW QUESTIONS

Chapter 10 Java and SQL. Wang Yang

1. PhP Project. Create a new PhP Project as shown below and click next

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

Database connectivity (II)

Three-Tier Architecture

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

Database Application Development

Database Application Development

Introduction to Databases

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

Databases - Relational Algebra. (GF Royle, N Spadaccini ) Databases - Relational Algebra 1 / 24

This lecture. Projection. Relational Algebra. Suppose we have a relation

Database Application Development

Visit for more.

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

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

Database Applications (15-415)

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

SQL-PL Interface. Murali Mani. Perl /CGI with Oracle/mySQL Install your own web server and use servlets with JDBC and Oracle/mySQL

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018

PERSİSTENCE OBJECT RELATİON MAPPİNG

CS221 Lecture: Java Database Connectivity (JDBC)

Relational terminology. Databases - Sets & Relations. Sets. Membership

Web Applications and Database Connectivity using JDBC (Part II)

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY

Database Application Development

Tiers (or layers) Separation of concerns

CHAPTER 44. Java Stored Procedures

Databases and SQL Lab EECS 448

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

Instructor: Jinze Liu. Fall 2008

Unit 3 - Java Data Base Connectivity

Chapter 1 An introduction to relational databases and SQL

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

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

DB I. 1 Dr. Ahmed ElShafee, Java course

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

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

Java E-Commerce Martin Cooke,

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

Top 50 JDBC Interview Questions and Answers

Transcription:

This lecture Databases - I The lecture starts discussion of how a Java-based application program connects to a database using. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 1 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 2 / 24 Application Programs Database Access End Users The mysql client program provides a low-level interface to the raw commands of MySQL, and as such is suitable only for expert users writing their own SQL/MySQL queries. However there are many reasons to connect other application programs to an SQL and/or MySQL database these programs may essentially be about providing access to the database in a special way or they may just use the database in the background to provide other functionality. An organization is likely to have only a few DBA professionals, but many more users who need to query the database. Suitable client programs can be written to provide simplified interfaces, usually graphical user interfaces for end-users. These interfaces would usually Customize the handling and error-checking of input Construct valid SQL queries from the input Run the SQL queries against the database Customize and format the output (GF Royle 2006-8, N Spadaccini 2008) Databases - I 3 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 4 / 24

Database Access Expert Users Database Integration A second use for additional client programs would be to provide expert users with specialized tools for visualizing and working with a whole database we have already seen such a tool in DBVisualizer and there are many more such tools. As well as client programs whose primary purpose is providing database access, there are many situations where a client program may benefit from database integration. In this situation the client program may wish to use a database in order to accomplish its primary purpose for example, a management information system may access a database to obtain recent sales figures, but then perform significant additional processing or analysis on the results. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 5 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 6 / 24 Database Backed Applications Connecting A third reason to connect an application to a database is to use the database as a tool to provide the essential functionality of the application here the database is supporting the use of the application, rather than the application supporting the use of the database. The typical example of such an application is a web-based bulletin board system where users post and view comments, perform searches and so on. Frequently the actual comments are stored in a database, and the web-pages that are displayed are constructed on-the-fly from the results of database queries. In this situation the user may not even be aware of the underlying database. There are many different ways of connecting an application written in a general purpose programming language (henceforth called the host language) to a MySQL server. The C API is a low-level client library for connecting C programs directly to a MySQL server. The Perl and PHP APIs provide higher level APIs for connecting to a number of different databases from Perl or PHP respectively is a standard API for connecting Java programs to a number of different databases. In this unit, will consider how to connect Java and PHP applications to MySQL. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 7 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 8 / 24

What is? Conceptual Diagram stands for Java DataBase Connectivity it is an API (Application Programmers Interface) that defines a set of interfaces for interaction with a database. Each database vendor writes a specific driver which is a set of classes that implements the interface on their database. For example, Oracle has a driver for Oracle databases, MySQL has a driver for MySQL databases and so on. If the application programmer also writes code that conforms to the standard, then the application can interact with a number of different databases simply by loading a different driver. Diagram from Java Enterprise in a Nutshell by Crawford, Farley & Flanagan, O Reilly. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 9 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 10 / 24 Architecture A (Java DataBase Connectivity) application can be viewed as consisting of four components The Java application program The application initiates a connection with the server, submits SQL statements and processes the results. The driver manager The driver manager loads drivers and passes the calls to the correct driver. The drivers A driver is database-specific code that translates calls into the right form for its particular database, and translates the results back into the standard. The data sources The underlying database or databases. Basics A application must perform the following steps: Load the driver class for the particular database being used. Open a connection to the database. Create SQL queries and use the connection to execute them. Process the results obtained from the database. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 11 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 12 / 24

Loading a driver Opening a connection A driver is loaded by using Java s dynamic loading mechanism Class.forName with the correct driver name, which for the MySQL driver is com.mysql.jdbc.driver. This method might throw an exception, so this must be caught. try { Class.forName("com.mysql.jdbc.Driver"); catch (ClassNotFoundException e) { System.out.println("Cannot load Driver"); Once the driver has been loaded the static methods in the class DriverManager 1 become available; the important method here is the method public static Connection getconnection(string url) throws SQLException This method takes a String in a URL-like format jdbc:driver:database which specifies, then the name of the driver and then connection details for the database (user name, password if any, and database). 1 The -related classes discussed here are in the package java.sql (GF Royle 2006-8, N Spadaccini 2008) Databases - I 13 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 14 / 24 Opening a local connection Statements Connecting as the root user to the world database stored on a MySQL server running on the local host would be done as follows: try { String url = "jdbc:mysql://localhost/world?user=root"; Connection conn = DriverManager.getConnection(url); catch (SQLException e) { System.out.println("Cannot open Connection"); System.exit(0); The precise form of the URL will depend on the particular driver, but in all cases the result is the object conn which represents an open connection to the database. An object from the Statement class is used to send your SQL statements to the database such an object is obtained from the Connection object that we just obtained from the DriverManager. try { String url = "jdbc:mysql://localhost/world?user=root"; Connection conn = DriverManager.getConnection(url); Statement stmt = conn.createstatement(); catch (SQLException e) { System.out.println("Cannot open Connection"); System.exit(0); (GF Royle 2006-8, N Spadaccini 2008) Databases - I 15 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 16 / 24

Queries Executing a query An actual SQL query is executed by the method public ResultSet executequery(string sql) of the Statement object. A query that executes successfully returns a ResultSet object which represents the table that the SQL query returns. It is important to note that the ResultSet object belongs to the Statement object and that if the Statement object is re-used for another query, then the ResultSet object will also be closed. Suppose we simply want to execute a query that returns the data stored in the country table from our database. Statement stmt = conn.createstatement(); String sql = "SELECT * FROM country"; ResultSet rs = stmt.executequery(sql); (This code must all be placed within the try/catch clause because pretty much all of these methods might throw an SQLException.) (GF Royle 2006-8, N Spadaccini 2008) Databases - I 17 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 18 / 24 Processing the results Changing the current row The key methods for moving through a ResultSet are A ResultSet object can be viewed as a table of results that can be stepped through row-by-row at each stage the object has a notion of a current row. In order to process the results we need methods to Change the current row Determine column values from the current row public boolean first() This moves to the first row of the result set public boolean next() This moves to the next row of the result set, returning false if there are no further rows to move to. In earlier versions of a result set could only be processed by starting at the first row and going through one row at a time. This is still the specification of the default ResultSet but the MySQL drivers return a scrollable ResultSet no matter what you ask for. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 19 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 20 / 24

Process each row Reading column values Thus to examine each row in turn uses code of the following form (assume that rs has already been obtained in the manner described above). while (rs.next()) { // process the row Reading a column value from the current row of the ResultSet is done by one of the getxxx() methods, where XXX is a Java type. For example, any column that is a CHAR, VARCHAR or TEXT type in the database can be accessed by using getstring(string columnname) getstring(int columnindex) where the column to be retrieved can either be specified by name or by position. Just to confuse everyone, the columns in SQL are indexed from position 1, not the 0-based indexing of Java, C, C++ etc. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 21 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 22 / 24 Brief Example What have we achieved? This code simply pulls out the columns name and population from each row of the ResultSet and prints them out. while (rs.next()) { String cntry = rs.getstring("name"); long popn = rs.getlong("population"); In one sense, all we have done is written a Java client program that executes the SQL statement SELECT name, population FROM country; in a round-about way. System.out.println(cntry+" "+popn); The important thing to realize is that we now have the database data inside the Java program where it can be post-processed in any number of ways. (GF Royle 2006-8, N Spadaccini 2008) Databases - I 23 / 24 (GF Royle 2006-8, N Spadaccini 2008) Databases - I 24 / 24