SQL and Java The vision for Java is to be the concrete and nails that people use to build this incredible network system that is happening all around us.

Slides:



Advertisements
Similar presentations
16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
Object-Oriented Enterprise Application Development Introduction to JDBC.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
CS 405G: Introduction to Database Systems Database programming.
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.
Relational Databases CS 240. Database Management Systems (DBMS)  Databases are implemented by software systems called Database Management Systems (DBMS)
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
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.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
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.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
JDBC (Java Database Connectivity)
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
SQL and Java The vision for Java is to be the concrete and nails that people use to build this incredible network system that is happening all around us.
Web Programming Assistant Professor Xiaozhong Liu
1 JDBC – Java Database Connectivity CS , Spring 2010.
JDBC I IS Why do we have databases?
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
JDBC.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Database Programming Basic JDBC Programming Concepts.
CompSci 280 S Introduction to Software Development
CS3220 Web and Internet Programming Database Access with JDBC
Java Access to RDB Relational databases (RDBs) dominate today, due to:
JDBC 15-Apr-18.
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
UNIT-2 Java Database Programming
JDBC.
Introduction to Server-Side Web Development using JSP and Databases
JDBC 15-Nov-18.
Interacting with Database
MSIS 655 Advanced Business Applications Programming
Using a Database with JDBC
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

SQL and Java The vision for Java is to be the concrete and nails that people use to build this incredible network system that is happening all around us James Gosling, 2000

Development with Java  Java is a platform-independent object- oriented development language  A simple approach to the development, management,and deployment of client/server and browser applications

JDBC  Java database connectivity (JDBC) is modeled on ODBC  Enables development of applications that are OS and DBMS independent

JDBC Application JDBC API JDBC driver manager Service provider API Driver for DBMS server DBMS server

JDBC  JDBC has seven interfaces and two classes  Interfaces need to be written for a specific DBMS  An interface is a group of related methods with empty bodies  A driver must be installed before you can access a specific DBMS  devapp.sun.com/product/jdbc/drivers devapp.sun.com/product/jdbc/drivers

Java EE  Java EE (Java Enterprise Edition) is a platform for multi-tiered enterprise applications  In the typical three-tier model, a Java EE application server sits between the client’s browser and the database server  A Java EE compliant server, of which there are a variety, is needed to process JSP

Installing the MySQL driver/connector  Download and unpack the latest version of the connector   Copy MySQL connector JAR file to the Java extensions folder  mysql-connector-java-5.1.xx*-bin.jar  OS X  Macintosh HD/System/Library/Java/Extensions  Windows  c:\jre\lib\ext * xx is the release number

Connecting to the DBMS  Supply the  url  account  password  Format of the url varies with the driver jdbc:mysql://

Connecting to the DBMS try { conn = DriverManager.getConnection(url, account, password); } catch(SQLException error) { System.out.println(“Error connecting to database: “ + error.toString()); System.exit(1); }

Create and execute an SQL statement  Create a Statement object  prepareStatement ()  Set the value of the query’s parameters using a set method  Execute the query  executeQuery()  Results are returned in a ResultSet object

Create and execute SQL statement try { stmt = conn.prepareStatement("SELECT shrfirm, shrdiv FROM shr WHERE shrdiv > ?"); // set the value for shrdiv to indiv stmt.setInt(1,indiv); rs = stmt.executeQuery(); } catch (SQLException error) { System.out.println("Error reporting from database: " + error.toString()); System.exit(1); }

Report a SELECT  The rows in the table are processed a row at a time using the next method of the ResultSet object  Columns are retrieved one at a time using a get… methods  getString()  getInt()

Report a SELECT while (rs.next()) { String firm = rs.getString(1); int div = rs.getInt(2); System.out.println(firm + " " + div); }

Create, execute, and report an SQL query try { stmt = conn.prepareStatement("SELECT shrfirm, shrdiv FROM shr WHERE shrdiv > ?"); // set the value for shrdiv to indiv stmt.setInt(1,indiv); rs = stmt.executeQuery(); while (rs.next()) { String firm = rs.getString(1); int div = rs.getInt(2); System.out.println(firm + " " + div); } catch (SQLException error) { System.out.println("Error reporting from database: ” + error.toString()); System.exit(1); }

Inserting a row try { stmt = conn.prepareStatement("INSERT INTO alien (alnum, alname) VALUES (?,?)"); stmt.setInt(1,10); stmt.setString(2, "ET"); stmt.executeUpdate(); } catch (SQLException error) { System.out.println("Error inserting row into database: " + error.toString()); System.exit(1); }

Closing  Close the statement, result set, and connection stmt.close(); rs.close(); conn.close();

Database access  A complete Java program and a main for testing it are available  DatabaseTest.java DatabaseTest.java  DatabaseAccess.java DatabaseAccess.java  Import the files into Eclipse and run the program

Art collection

ArtCollector.java (1) public class ArtCollector { private String jdbc = "jdbc:mysql:"; private String database = "Art"; private String account = "root"; private String password = ""; private String url = "//localhost:3306/" + database; private Connection conn; private ResultSet rs; private PreparedStatement stmt; private CsvReader input; private URL csvurl; private int artistPK;

ArtCollector.java (2) public void addRecords() { try { csvurl = new URL(" // get the URL } catch (IOException error) { System.out.println("Error accessing url: " + error.toString()); System.exit(1); } conn = getConnection(); // connect to the database

ArtCollector.java (3) try { input = new CsvReader(new InputStreamReader(csvurl.openStream())); input.readHeaders(); while (input.readRecord()) { // Artist String firstName = input.get("firstName"); String lastName = input.get("lastName"); String nationality = input.get("nationality"); int birthYear = Integer.parseInt(input.get("birthyear")); int deathYear = Integer.parseInt(input.get("deathyear")); artistPK = addArtist(conn, firstName, lastName, nationality, birthYear, deathYear); // Painting String title = input.get("title"); double length = Double.parseDouble(input.get("length")); double breadth = Double.parseDouble(input.get("breadth")); int year = Integer.parseInt(input.get("year")); addArt(conn, title, length, breadth, year,artistPK); } input.close();

ArtCollector.java (4) public int addArtist(Connection conn, String firstName, String lastName, String nationality, int birthYear,int deathYear) { int autoIncKey = 0; try { stmt = conn.prepareStatement("INSERT INTO artist (firstName, lastName, birthyear, deathyear, nationality) VALUES ( ?, ?, ?, ?, ?)"); stmt.setString(1,firstName); stmt.setString(2,lastName); stmt.setInt(3,birthYear); stmt.setInt(4,deathYear); stmt.setString(5,nationality); stmt.executeUpdate(); System.out.println(stmt); // get the autoincremented identifier to use as a foreign key rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); if (rs.next()) { autoIncKey = rs.getInt(1); } rs.close(); } catch (SQLException error) {…

ArtCollector.java (4) public void addArt(Connection db, String title, double length, double breadth, int year,int artistPK) { try { stmt = db.prepareStatement("INSERT INTO art (title, length, breadth, year, artistid) VALUES (?,?,?,?,?)"); stmt.setString(1,title); stmt.setDouble(2,length); stmt.setDouble(3,breadth); stmt.setInt(4,year); stmt.setInt(5,artistPK); stmt.executeUpdate(); System.out.println(stmt); } catch (SQLException error) { System.out.println("Error inserting Art into database: " + error.toString()); System.exit(1); }

Art collection  A complete Java program and a main for testing it are available  DatabaseTest.java DatabaseTest.java  ArtCollection.java ArtCollection.java  Import the files into Eclipse and run the program

Map collection

Data entry

index.html(1) Map collection

Index.html(2) Map identifier: Map scale: Map type: Bicycle Canal Rail Road

index.html(3) Countries: Austria Germany Liechtenstein Switzerland

Transaction processing  A transaction is a logical unit of work  Insert one row in map  Insert one row in MAP-COUNTRY for each country on the map  All inserts, updates, and deletes must complete successfully for atransaction to be processed  COMMIT  Transaction successful  ROLLBACK  Transaction failure

AUTOCOMMIT  Turn off autocommit to enable COMMIT and ROLLBACK try { conn.setAutoCommit(false); } catch (SQLException error){ System.out.println("Error with autocommit" + error.toString()); System.exit(1); }

COMMIT try { conn.commit(); System.out.println(“Transaction commit”); } catch (SQLException error){ System.out.println("Error with commit" + error.toString()); System.exit(1); }

ROLLBACK try { conn.rollback(); System.out.println("Transaction rollback"); } catch (SQLException error){ System.out.println("Error with rollback" + error.toString()); System.exit(1); }

mapinsert.jsp(1) page language="java" contentType="text/html; charset=ISO " pageEncoding="ISO "%> Map insert page <%

mapinsert.jsp(2) String url; String jdbc = "jdbc:mysql:"; String database = "//localhost:3306/MapCollection"; String username = "root", password = ""; String mapid, maptype, countries; String[] country; int mapscale = 0; boolean transOK = true; PreparedStatement insertMap; PreparedStatement insertMapCountry; Connection conn=null;

mapinsert.jsp(3) // make connection url = jdbc + database; try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException error) { System.out.println("Error connecting to database: " + error.toString()); System.exit(1); } try { conn.setAutoCommit(false); } catch (SQLException error) { System.out.println("Error turning off autocommit" + error.toString()); System.exit(1); }

mapinsert.jsp(4) //form data mapid = request.getParameter("mapid"); mapscale = Integer.parseInt(request.getParameter("mapscale")); maptype = request.getParameter("maptype"); country = request.getParameterValues("countries"); transOK = true; // insert the map try { insertMap = conn.prepareStatement("INSERT INTO map (mapid, mapscale, maptype) VALUES (?,?,?)"); insertMap.setString(1, mapid); insertMap.setInt(2, mapscale); insertMap.setString(3, maptype); System.out.println(insertMap); insertMap.executeUpdate();

mapinsert.jsp(5) // insert the countries for (int loopInx = 0; loopInx < country.length; loopInx++) { insertMapCountry = conn.prepareStatement("INSERT INTO mapCountry (mapid,cntrycode ) VALUES (?,?)"); insertMapCountry.setString(1, mapid); insertMapCountry.setString(2, country[loopInx]); System.out.println(insertMapCountry); insertMapCountry.executeUpdate(); } } catch (SQLException error) { System.out.println("Error inserting row: " + error.toString()); transOK = false; }

mapinsert.jsp(6) if (transOK) { conn.commit(); // all inserts successful System.out.println("Transaction commit"); } else { conn.rollback(); // at least one insert failed System.out.println("Transaction rollback"); } conn.close(); System.out.println("Database closed"); %>

Map collection  A complete Java program and a main for testing it are available  index.html index.html  mapinsert.java mapinsert.java  Import the files into Eclipse (Indigo) and run the program

Conclusion  Java can be used to developed interoperable multi-tier applications  JDBC is the key technology for accessing a relational database  Java is well-suited for processing transactions that amend a relational database