Accessing databases in Java using JDBC

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

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

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

Databases and SQL Lab EECS 448

Java Database Connectivity

Java Database Connectivity (JDBC) 25.1 What is JDBC?

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

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

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

Instructor: Jinze Liu. Fall 2008

PERSİSTENCE OBJECT RELATİON MAPPİNG

Lab # 9. Java to Database Connection

SQream Connector JDBC SQream Technologies Version 2.9.3

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

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

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

13 Creation and Manipulation of Tables and Databases

Databases 2012 Embedded SQL

Working with Databases and Java

Chapter 1 An introduction to relational databases and SQL

Server-side Web Programming

DATABASE DESIGN I - 1DL300

SQL in a Server Environment

Visit for more.

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

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

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

Java Database Connectivity

SQL DML and DB Applications, JDBC

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

Servlet 5.1 JDBC 5.2 JDBC

COMP102: Introduction to Databases, 23

Introduction to relational databases and MySQL

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

Tiers (or layers) Separation of concerns

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

Database Application Development

Accessing a database from Java. Using JDBC

Java Database Connectivity

Chapter 10 Java and SQL. Wang Yang

Pieter van den Hombergh. March 25, 2018

Advanced Programming Techniques. Database Systems. Christopher Moretti

Unit 3 - Java Data Base Connectivity

Programming in Java

Database Application Development

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

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

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

Application Programming for Relational Databases

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

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

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

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

Lecture 2. Introduction to JDBC

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

Chapter 9 SQL in a server environment

JDBC 3.0. Java Database Connectivity. 1 Java

UNIT-3 Java Database Client/Server

Chapter 4 Application Programs and Object-Relational Capabilities

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 9. Nadia Polikarpova

UNIT III - JDBC Two Marks

WEB SERVICES EXAMPLE 2

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

Introduction to Databases [p.3]

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

Introduction to SQL & Database Application Development Using Java

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

JDBC, Transactions. Niklas Fors JDBC 1 / 38

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

Database Application Development

Chapter 16: Databases

COMP 430 Intro. to Database Systems. SQL from application code

Non-interactive SQL. EECS Introduction to Database Management Systems

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

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Databases CSCI 201 Principles of Software Development

SQL and Java. Database Systems Lecture 20 Natasha Alechina

General Overview - rel. model. Carnegie Mellon Univ. Dept. of Computer Science Database Applications. Reminder: our Mini-U db

JAVA AND DATABASES. Summer 2018

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!

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

MySQL for Developers Ed 3

Introduction to SQL Server. nikos bikakis

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

MySQL for Developers Ed 3

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

Database Applications (15-415)

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

Oracle Exam 1z0-809 Java SE 8 Programmer II Version: 6.0 [ Total Questions: 128 ]

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

DB I. 1 Dr. Ahmed ElShafee, Java course

What is Transaction? Why Transaction Management Required? JDBC Transaction Management in Java with Example. JDBC Transaction Management Example

INTRODUCTION TO JDBC - Revised Spring

Chapter 13 Introduction to SQL Programming Techniques

Unit 27 Web Server Scripting Extended Diploma in ICT

CSC 215 PROJECT 2 DR. GODFREY C. MUGANDA

JDBC [Java DataBase Connectivity]

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

Introduction to JDBC. Lecture 12

Lab 6-1: MySQL Server

Transcription:

Accessing databases in Java using JDBC Introduction JDBC is an API for Java that allows working with relational databases. JDBC offers the possibility to use SQL statements for DDL and DML statements. This API can be regarded as an abstraction layer between the application and the DBMS, programmers being able to work with the database independent of the underlying DBMS. Thus the code does not suffer modifications if the DBMS is changed. This independence is achieved by the fact that JDBC uses drivers, which translate JDBC API method calls to specific DBMS API. When we change the DBMS it is enough to change the driver, which can be done even at runtime. (Note: Database notions are assumed to be known by the students, this lesson is focused only on using JDBC). In addition to executing SQL statements, JDBC allows us to invoke stored procedures which are specific to the used DBMS. Requirements In this exercise we are using an the MySQL relational database that can be downloaded from https://dev.mysql.com/downloads/mysql/. The scripts for database creation will be provided in the tutorial, for easier manipulation of the database you can install MySQL Workbench, a visual tool for database administrators ( https://www.mysql.com/products/workbench/ ) The used IDE is Netbeans (http://netbeans.org/ )

Creating the database Install MySQL (and optionally MySQL workbench) if you have not done it until this step. Make sure that mysql is running. The following commands are entered from command line. mysql -u root -p Logs in to mysql as admin. You need to enter the password. CREATE DATABASE jdbcex Creates a new database called jdbcex. SHOW DATABASES Check that the database has been created We should also create a user that can access this database to avoid the security risk of using the admin user. CREATE USER 'jdbcuser'@'localhost' IDENTIFIED BY 'password' GRANT ALL PRIVILEGES ON jdbcex.* TO 'jdbcuser'@'localhost' FLUSH PRIVILEGES Connect to the database USE jdbcex We will create a simple database consisting of a Persons table and an Addresses table. CREATE TABLE addresses ( id INT NOT NULL AUTO_INCREMENT, city VARCHAR(45) NOT NULL, street VARCHAR(45) NULL, PRIMARY KEY ( id )); CREATE TABLE `persons` (

`id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `address` INT NULL, PRIMARY KEY (`id`), INDEX `fk_address_idx` (`address` ASC), CONSTRAINT `fk_address` FOREIGN KEY (`address`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION); Finally let us introduce some records INSERT INTO `addresses` (`city`, `street`) VALUES ('Bucuresti', 'Politehnicii'); INSERT INTO `addresses` (`city`, `street`) VALUES ('Ploiesti', 'Independetei'); INSERT INTO `persons` (`name`, `address`) VALUES ('Vasile', '1'); INSERT INTO `persons` (`name`, `address`) VALUES ('John', '1'); INSERT INTO `persons` (`name`, `address`) VALUES ('Emily', '2'); Accessing a database using JDBC

Basic steps Create a new Java Application project in Netbeans. Add the MySQL JDBC driver. (Libraries -> Add Library -> MySQL JDBC DRIVER) We go through the following steps for accessing a database: 1. Making the connection A connection is identified by an URL with the syntax: jdbc:<protocol>:<nameofdatabase> In our case the URL has the form: jdbc:mysql://localhost:3306/jdbcex We also need a username and a password for connecting to the database ( In our case username = jdbcuser, and the password is password). This three arguments (nameofdatabase, user, password) should not be hardcoded in the application but instead saved in an external file (for example using java.util.properties) so you can have a reusable class for connecting to the database. So let`s save the url in a string: String url = "jdbc:mysql://localhost:3306/jdbcex"; (note that the port number is 3306 for MySQL) and then connect to the database: Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, "jdbcuser", "password"); 2. Execute an SQL statement First we create a Statement from the Connection: Statement instr=con.createstatement(); then we execute this statement. In case of a SELECT statement we use executequery() which returns a ResultSet and in case of an UPDATE, DELETE, INSERT, CREATE TABLE, DROP TABLE we use executeupdate() which returns the number of affected rows. (except for create and drop where it returns 0). 3. Retrieve values from the ResultSet

JDBC returns results in a ResultSet object: String sql = "SELECT * FROM persons"; ResultSet rs=instr.executequery(sql); while(rs.next()){ System.out.println(rs.getString("name")); } rs.next() points the cursor of the resultset to the next position (initially it is before the first record). The values are extracted using getx() methods where x is the data type and the argument is the position of the column in the table. We could have also used the name of the column : 4. Close the connection ResultSet, Statement must be closed first: rs.close(); instr.close(); and then the Connection: con.close(); The complete program : import java.sql.*; public class Main { public static void main(string[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:mysql://localhost:3306/jdbcex"; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, "jdbcuser", "password"); Statement instr = con.createstatement(); String sql = "SELECT * FROM persons"; ResultSet rs = instr.executequery(sql); while (rs.next()) { System.out.println(rs.getString("name")); } rs.close(); instr.close();

} } con.close(); Using JOIN Suppose you want to use more tables to perform a certain operation. In this case you join the tables using a value they have in common. (usually a foreign key). In our case we join persons and addresses using persons.address and addresses.id fields: SELECT p.name, a.city FROM persons p INNER JOIN addresses a ON p.address = a.id WHERE a.city = 'Bucuresti'