INTRODUCTION TO JDBC - Revised spring

Similar documents
INTRODUCTION TO JDBC - Revised Spring

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

JAVA AND DATABASES. Summer 2018

Database Application Development

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

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

DATABASE DESIGN I - 1DL300

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Databases 2012 Embedded SQL

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

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

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

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

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

Database Application Development

Database Application Development

SQL in a Server Environment (ii)

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

JDBC, Transactions. Niklas Fors JDBC 1 / 38

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

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

Tutorial: Using Java/JSP to Write a Web API

Database connectivity (II)

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

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

Database Application Programs PL/SQL, Java and the Web

Database Application Development

SQL in a Server Environment

Lecture 27 10/30/15. CMPSC431W: Database Management Systems. Instructor: Yu- San Lin

Instructor: Jinze Liu. Fall 2008

O ne of the most important features of JavaServer

PERSİSTENCE OBJECT RELATİON MAPPİNG

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

Application Programming for Relational Databases

DB I. 1 Dr. Ahmed ElShafee, Java course

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

Persistency Patterns. Repository and DAO

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Programming in Java

JDBC 3.0. Java Database Connectivity. 1 Java

Advances in Programming Languages

Real SQL Programming 1

SQL and Java. Database Systems Lecture 20 Natasha Alechina

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

Advances in Programming Languages

13 Creation and Manipulation of Tables and Databases

Chapter 13 Introduction to SQL Programming Techniques

Working with Databases and Java

Chapter 3 DB-Gateways

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Database Applications. SQL/PSM Embedded SQL JDBC

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

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

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

Chapter 3 DB-Gateways

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

CHAPTER 44. Java Stored Procedures

Chapter 4 Application Programs and Object-Relational Capabilities

Database Explorer Quickstart

SQL in a Server Environment

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

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

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

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

Server-side Web Programming

Database Design and Programming

SQL DML and DB Applications, JDBC

Week - 01 Lecture - 04 Downloading and installing Python

Chapter 3 DB-Gateways

IBM DB DB2 application development Hands-On Lab. Information Management Cloud Computing Center of Competence. IBM Canada Lab

Accessing a database from Java. Using JDBC

Tiers (or layers) Separation of concerns

Why use a database? You can query the data (run searches) You can integrate with other business systems that use the same database You can store huge

Database-Connection Libraries. Java Database Connectivity PHP

Database-Connection Libraries

Java Database Connectivity

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

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

Database Assignment 2

JDBC Programming: Intro

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

Lesson 13 Transcript: User-Defined Functions

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

Chapter 9 SQL in a server environment

JDBC [Java DataBase Connectivity]

Optimize Enterprise Generation Language (EGL) applications using purequery

Database Application Development Part 2 - Chapter

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

SqlC tutorial. 12 th may Revision 1.0. Visit us at

These notes add to the JDBC discussion your textbook.

Chapter 9 SQL in a server environment

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

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

Embedded SQL. Introduction

Embedded SQL. Davood Rafiei

Accessing databases in Java using JDBC

CSE 308. Database Issues. Goals. Separate the application code from the database

APCS Semester #1 Final Exam Practice Problems

The Web Application Developer s. Red Hat Database. View. October 30, Webcast. Patrick Macdonald, Fernando Nasser. Red Hat Database Engineering

Transcription:

INTRODUCTION TO JDBC - Revised spring 2004 -

1 What is JDBC? Java Database Connectivity (JDBC) is a package in the Java programming language and consists of several Java classes that deal with database issues such as connections, queries etc. Included in the Java toolkit is the JDBC-ODBC Bridge driver but there are other specific drivers available from different database manager manufacturers. In this introduction we ll be using the DB2 JDBC driver from IBM named: COM.ibm.db2.jdbc.app.DB2Driver. This is important since different drivers do not always act the same way. To be able to compile and execute a Java program that uses the JDBC framework you need to have two things. First, you need to have the Java Standard Development Toolkit (SDK) installed. This environment is free of charge and could be downloaded from: http://java.sun.com/j2se/1.4.2/download.html Secondly, you need to have a ODBC or a JDBC driver installed that corresponds to the database management system (DBMS) you are using or plan to use. These drivers are often supplied by the DBMS manufacturers. Just similar to any Java application a JDBC enabled Java application is compiled through the Java compiler javac. The compiler creates machine readable (executable) code out of your Java source code which could be executed through the virtual machine by the java command. 2 An example (JDBCAppa): On the on the local network path: \\db-srv-1\studkursinfo\is4 vt2004\myjdbctest you ll find the file JDBCAppa.java. This is the complete source code of this example and there you ll see all syntax used in this introduction in its context. 1. First of all, create a new folder (preferably on your m: drive) and name it something convenient like for example myjdbc. 2. Copy the source file JDBCAppa.java to your new folder. Now, the JDBCAppa.java file is not compiled yet, as you ll see if you open it in a text editor like for example notepad. It s is still in a high level programming language, which is easily readable and meaningful for the human eye. This means that the application cannot be executed since what tends to be readable for a computer is garble for humans and vice versa. 3. Compile the.java file by using the javac compiler to create a new.class file. Do this by placing yourself in the newly created folder in a Windows Command Prompt (in this case m:\myjdbc) and issue the command: javac JDBCAppa.java As you ll see, this procedure created the file JDBCAppa.class. This is the low level language and virtual machine specific instructions understood by the computer (and not by humans). Hopefully you now have two versions of the application. One that you are able to read, the other meaningful for the computer. Execute the application by using the virtual machine caller command: java JDBCAppa. Every time you change something in the source code you have to recompile the.class file to see the effects when running the application. 2.1 Explanation of the source code Open up JDBCAppa.java to view the application source code. Exactly as the compiler and the virtual machine (VM), we ll go through the file, reading from the top. 2

import java.sql.* This is a statement to include compiled Java methods and constructs from other packages. The star * states that we shall include all classes in the java.sql package path. This is the package that includes all JDBC components that we are interested in. static protected Connection con; private String URL = jdbc:db2:sample ; private String userid = ; private String driver = COM.ibm.db2.jdbc.app.DB2Driver ; private String password = ; This section creates a lot of variables. con is the variable that is going to manage out database connection, URL is the path of our database, driver specifies where the driver details are located and userid and password are giving the required information to log on to the database. After the variables are created, the compiler/vm call the main method which in turn call out to the connect, select and update methods. 2.1.1 The connect method class.forname(getdriver()); This method loads the specified driver. con = DriverManager.getConnection(getURL(), getuserid(), password); This creates a connection instance and attaches this to the con handle created earlier. The connection instance connects to the DB2 database by the help of the URL, userid and password variables. con.setautocommit(false); This specifies that all changes made in the database are not inserted until an explicit commit command is issued. If autocommit is turned on, every query is committed directly after it has been executed. 2.1.2 The select method At first the variables query (String), rs (ResultSet) and stmt (Statement) are declared. Query holds the SQL string that s specifying what we are looking for, rs is the variable that is going to keep the query results and stmt is the variable that executes the query against the database connection. query = SELECT empno, firstnme FROM employee; ; This specifies our query which will collect all employment numbers and first names of all employees registered in the database. 3

stmt = con.createstatement(); The stmt handle is associated with a statement object that in turn is linked with the database connection. rs = stmt.executequery(query); This statement executes the SQL query specified in the string query against the connection specified in stmt. The result of the query is put in rs. while(rs.next()){ System.out.print( empno= +rs.getstring( empno )); System.out.print( ); System.out.println( firstname= +rs.getstring( firstnme )); } This WHILE-loop iterates through the collected rows in the data collection rs until the last row is fetched. The method next returns false when the collection is empty, ending the WHILE-loop. For each iteration the metod getstring retrieves the value of the column specified in its argument. For example rs.getstring( firstnme ) retrieves the value of the column named firstnme in the fetched row. It is also possible to use other methods to collect values of different data types like Integers or Booleans. For example specifying rs.getfloat(6) would retrieve the sixth column in the row and treat the collected value as a Float. This can be seen in the last part of the select method in JDBCAppa where a nondecimal number is fetched by the getint method. 2.1.3 The update method This is a little different then the previous method since we re not retrieving anything, only changing old or inserting new data. In this case we re also interested in working with dynamic parameters that are changed during the execution of the program. To do this we use the PreparedStatement class instead of Statement. The main difference is that PreparedStatement uses? signs as dynamic parameters. Consider the following: query = UPDATE employee SET firstnme = SHILI WHERE empno =?; ; This creates an ordinary SQL string with the exchangeable parameter?. stmt = con.preparedstatement(query); This does exactly the same as when declaring the statement in the select method, although this is a PreparedStatement. stmt.setstring(1,param1); This is interesting since it changes the first? parameter of the query specified in stmt to the content of the string param1. The first integer argument specifies which parameter 4

number should be changed. For example setstring(5, Mike ) would have changed the fifth question mark with the text Mike. stmt.executeupdate(); This would execute the update in the database. Note that since we don t collect any data we don t need any ResultSet to capture it in. 3 Additional information: JDBC Tutorial: http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html Java Basics: http://java.sun.com/docs/books/tutorial/getstarted/cupojava/win32.html java.sql Documentation: http://java.sun.com/j2se/1.3/docs/api/java/sql/package-summary.html 4 Writing your first JDBC application It s greatly recommended to use your own folder under the m: drive as a base when creating the application. Try to reuse as much of the JDBCAppa.java as possible, modify it and make adjustments rather then starting from scratch. A few points to keep in mind when doing this: 1. The name of the file and the class must be the same. Renaming the class = renaming the file and vice versa. 2. The database path and login information must be correct in the application. 5