Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS)

Similar documents
Application Users. Application Programs. Some Reasons for Using a DBMS (Database Management System)

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

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

Environment Settings on SIT

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

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

Java application using JDBC to connect to a database.

Top 50 JDBC Interview Questions and Answers

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

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

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

Application Programming for Relational Databases

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

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

Server-side Web Programming

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

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

PERSİSTENCE OBJECT RELATİON MAPPİNG

Unit 3 - Java Data Base Connectivity

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

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

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle

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

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

UNIT III - JDBC Two Marks

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

Lecture 2. Introduction to JDBC

Java Database Connectivity (JDBC) 25.1 What is JDBC?

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

UNIT-3 Java Database Client/Server

Database Application Development

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

CS221 Lecture: Java Database Connectivity (JDBC)

JDBC [Java DataBase Connectivity]

SNS COLLEGE OF ENGINEERING, Coimbatore

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

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

Working with Databases and Java

Unit 2 JDBC Programming

Introduction JDBC 4.1. Bok, Jong Soon

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

Java Database Connectivity

SQL in a Server Environment

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

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

Chapter 16: Databases

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Programming in Java

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

Database Application Development

Database Application Development

Introduction to SQL & Database Application Development Using Java

Chapter 13 Introduction to SQL Programming Techniques

JDBC MOCK TEST JDBC MOCK TEST IV

PESIT Bangalore South Campus

Accessing databases in Java using JDBC

JDBC - INTERVIEW QUESTIONS

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

JAVA AND DATABASES. Summer 2018

Acknowledgments About the Authors

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

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

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

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

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

JDBC SHORT NOTES. Abstract This document contains short notes on JDBC, their types with diagrams. Rohit Deshbhratar [ address]

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

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

DB I. 1 Dr. Ahmed ElShafee, Java course

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

Lab # 9. Java to Database Connection

Java Database Connectivity

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Databases and SQL Lab EECS 448

Chapter 9 SQL in a server environment

Database connectivity (I) ()

Databases 2012 Embedded SQL

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

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

SQL and Java. Database Systems Lecture 20 Natasha Alechina

Pieter van den Hombergh. March 25, 2018

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

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

Database Application Development Part 2 - Chapter

Chapter 10 Java and SQL. Wang Yang

O ne of the most important features of JavaServer

13.1 Relational Databases (continued) 13.1 Relational Databases. - Logical model

13.1 Relational Databases

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

Database Applications. SQL/PSM Embedded SQL JDBC

JDBC Programming: Intro

INTRODUCTION TO JDBC - Revised Spring

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

Visit for more.

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

Table of Contents. Introduction... xxi

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

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

Database Application Development

Transcription:

Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS) Oracle JDBC Tutorial & Documentation http://docs.oracle.com/javase/tutorial/jdbc/basics/ Connector-J, MySql JDBC Driver Documentation, https://dev.mysql.com/doc/connector-j/5.1/en/ JDBC Drivers Java supports four types of JDBC drivers JDBC-ODBC bridge plus ODBC driver: Java code access ODBC native binary drivers, ODBC driver accesses databases, ODBC drivers must be installed on each client Native-API partly-java driver: Java code accesses database specific native binary drivers JDBC-Net pure Java driver: Java code accesses database via DBMS-independent net protocol Pure Java driver In a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible; you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically. 1

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. The JDBC API is comprised of two packages: java.sql javax.sql The JDBC Interfaces Driver Connection Connection Statement Statement Statement Statement ResultSet ResultSet ResultSet ResultSet Developing JDBC Programs 2

Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.jdbcodbcdriver Already in JDK MySQL com.mysql.jdbc.driver Oracle oracle.jdbc.driver.oracledriver Connection connection = DriverManager.getConnection(databaseURL); Database Access MySQL Oracle URL Pattern jdbc:odbc:datasource jdbc:mysql://hostname/dbname jdbc:oracle:thin:@hostname:port#:oracledbsid Examples: For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:examplemdbdatasource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@company.com:1521:orcl", "bob", "feiner"); Creating statement: Statement statement = connection.createstatement(); Executing statement (for update, delete, insert): statement.executeupdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = statement.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = stmt.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Processing ResultSet (for select): 3

// Iterate through the result and print the student names while (resultset.next()) System.out.println(resultSet.getString(1) + " " + resultset.getstring(2) + ". " + resultset.getstring(3)); Queries executeupdate Use for INSERT, UPDATE, DELETE or SQL that return nothing executequery Use for SQL (SELECT) that return a result set execute Use for SQL that return multiple result sets Uncommon ResultSet ResultSet - Result of a Query - JDBC returns a ResultSet as a result of a query - A ResultSet contains all the rows and columns that satisfy the SQL statement - A cursor is maintained to the current row of the data - The cursor is valid until the ResultSet object or its Statement object is closed - next() method advances the cursor to the next row - You can access columns of the current row by index or name 4

ResultSet has getxxx methods that: has either a column name or column index as argument returns the data in that column converted to type XXX getobject - An alternative to the getxxx method Rather than ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = tablelist.getstring( 1); - Can use ResultSet tablelist = gettables.executequery("select * FROM name"); String firstname = (String) tablelist.getobject( 1); getobject( int k) returns the object in the k th column of the current row getobject( String columnname) returns the object in the named column PreparedStatement The PreparedStatement interface is designed to execute dynamic SQL statements and SQLstored procedures with IN parameters. These SQL statements and stored procedures are precompiled for efficient use when repeatedly executed. Statement pstmt = connection.preparestatement ("insert into Student (firstname, mi, lastname) + values (?,?,?)"); Retrieving Database Metadata Database metadata is the information that describes database itself. JDBC provides the DatabaseMetaData interface for obtaining database wide information and the ResultSetMetaData interface for obtaining the information on the specific ResultSet. The DatabaseMetaData interface provides more than 100 methods for getting database metadata concerning the database as a whole. These methods can be divided into three groups: for retrieving general information, for finding database capabilities, and for getting object descriptions. The general information includes the URL, username, product name, product version, driver name, driver version, available functions, available data types and so on. Example: DatabaseMetaData dbmetadata = connection.getmetadata(); System.out.println("database URL: " + dbmetadata.geturl()); System.out.println("database username: " + dbmetadata.getusername()); 5

System.out.println("database product name: " + dbmetadata.getdatabaseproductname()); System.out.println("database product version: " + dbmetadata.getdatabaseproductversion()); System.out.println("JDBC driver name: " + dbmetadata.getdrivername()); System.out.println("JDBC driver version: " + dbmetadata.getdriverversion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close(); CallableStatement The CallableStatement interface is used to execute SQL-stored procedure/function. Example: drop function if exists studentfound; delimiter // create function studentfound(first VARCHAR(20), last VARCHAR(20)) returns int begin declare result int; select count(*) into result from Student where Student.firstName = first and Student.lastName = last; return result; end; // delimiter ; 6

mysql> select studentfound('king', 'Smith'); CallableStatement callablestatement = conn.preparecall( "{? = call studentfound(?,?)}"); java.util.scanner input = new java.util.scanner(system.in); String firstname = "Jacob"; String lastname = "Smith"; callablestatement.setstring(2, firstname); callablestatement.setstring(3, lastname); callablestatement.registeroutparameter(1, Types.INTEGER); callablestatement.execute(); if (callablestatement.getint(1) >= 1) { out.println(firstname + " " + lastname + " is in the database" + "<br>"); } else { out.println(firstname + " " + lastname + " is not in the database" + "<br>"); Data Conversion 7

Some Cautions Mixing ResultSets Can't have two active result sets on same statement Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = gettables.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); // Raises java.sql.sqlexception count.getobject(1); rugby.close(); this can happen when two threads have access to the same statement Two Statements on one Connection work Connection rugby; rugby = DriverManager.getConnection( dburl, user, password); Statement gettables = rugby.createstatement(); Statement tablesize = rugby.createstatement(); ResultSet count = gettables.executequery("select COUNT(*) FROM name"); ResultSet tablelist = tablesize.executequery("select * FROM name"); while (tablelist.next() ) System.out.println("Last Name: " + tablelist.getobject(1) + '\t' + "First Name: " + tablelist.getobject( "first_name")); count.next(); System.out.println("Count: " + count.getobject(1) ); count.close(); tablelist.close(); rugby.close(); Threads & Connections - Some JDBC drivers are not thread safe - If two threads access the same connection results may get mixed up MySql driver is thread safe - When two threads make a request on the same connection - The second thread blocks until the first thread get it its results - Can use more than one connection but - Each connection requires a process on the database To run the example code from NetBeans IDE Clean/build, deploy and run 8

To see query result from collegedb, type DatabaseAccess (Servlet name) as follows. 9

10