Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH

Slides:



Advertisements
Similar presentations
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
Advertisements

16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
1 CSE5200 JDBC and JDeveloper JDBC java.sql package java.sql classes.
Distributed Application Development B. Ramamurthy.
Fundamentals, Design, and Implementation, 9/e Chapter 14 JDBC, Java Server Pages, and MySQL.
JDBC Dr Jim Briggs. WEBP JDBC2 JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets) to databases Largely.
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Session-01. Hibernate Framework ? Why we use Hibernate ?
Dale Roberts 8/24/ Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Oracle8 JDBC Drivers Section 2. Common Features of Oracle JDBC Drivers The server-side and client-side Oracle JDBC drivers provide the same basic functionality.
JDBC. JDBC Drivers JDBC is an alternative to ODBC and ADO that provides database access to programs written in Java.
Databases: Queries with Java Dr Andy Evans. JDBC SQL Three methods: Statements: Standard, simple, SQL. PreparedStatements: Compiled SQL statements that.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
Object-Oriented Software How does it differ from procedural? How is it similar to procedural? Why has it become so popular? Does it replace or supplement.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Session 2 Tonight’s topics: 1.Prepared Statements 2.Transaction Processing 3.Callable Statements & Stored Procedures 4.Scrollable & Updatable Result.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
JDBC IV IS Outline  Quiz 1  Stored procedures  Batch processing  Transactions  Homework #2.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
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.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
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.
JDBC III IS Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.
JDBC and OCCI 10/29/2017.
DEPTT. OF COMP. SC & APPLICATIONS
CS3220 Web and Internet Programming Database Access with JDBC
1st Semester, 2017 Sanghyun Park
Web Technologies IT230 Dr Mohamed Habib.
Advanced Web Automation Using Selenium
HW#4 Making Simple BBS Using JDBC
Introduction to Server-Side Web Development using JSP and Databases
Java Database Connectivity
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Basic JDBC Use Oracle JDBC Drivers must be in the CLASSPATH import java.sql.*; … Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("Select LAST_NAME from PERSONS where ORG_UNIT like 'IT%'"); while (rset.next()) System.out.println(rset.getString("LAST_NAME")); rset.close(); stmt.close(); conn.close(); Load the Oracle JDBC driver Set which TNSNAMES file to use Create statement Specify the connection Execute query Obtain results Clean up Oracle JDBC Drivers must be in the CLASSPATH Preinstalled in the CERN Web Services infrastructure (thin) Obtaining drivers: Google for “Oracle JDBC Drivers” Oracle Tools and Bindings with languages

Oracle JDBC Driver Types Thin driver (works through TCP/IP) Pure Java Platform independent Does not require Oracle Client Installation Can be used in applets OCI driver (works through SQL*Net) Better performance Support OCI connection pooling Caching results in the client’s memory Requires Oracle Client Installation Should match the database version Platform specific Server-side internal driver (Java stored procedures) Oracle Tools and Bindings with languages

jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1 Connection Details jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1 Driver Type Username/password (optional) Connect string Connect string variants 1. @pdb2-v.cern.ch:1574/PDB_CERNDB1.cern.ch (no support for clustering, needs changing) 2. @(DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=pdb2-v.cern.ch) (PORT=1574) ) (ADDRESS= (PROTOCOL=TCP) (HOST=pdb1-v.cern.ch) (PORT=1574) )(FAILOVER=on) (LOAD_BALANCE=off)(CONNECT_DATA= (SERVER=DEDICATED) (SERVICE_NAME=PDB_CERNDB1.cern.ch)(FAILOVER_MODE= (TYPE=SELECT) (METHOD=BASIC)))) (long, needs changing after DB migration) 3. @cerndb1 (since 10.2.0.1.0, requires oracle.net.tns_admin property) TNSNAMES.ORA entry example cerndb1=(DESCRIPTION=(ADDRESS= (PROTOCOL=TCP) (HOST=pdb2-v.cern.ch) (PORT=1574) ) (ADDRESS= (PROTOCOL=TCP) (HOST=pdb1-v.cern.ch) (PORT=1574) ) (FAILOVER=on)(LOAD_BALANCE=off) (CONNECT_DATA= (SERVER=DEDICATED) (SERVICE_NAME=PDB_CERNDB1.cern.ch) (FAILOVER_MODE= (TYPE=SELECT) (METHOD=BASIC)))) Oracle Tools and Bindings with languages

Basic JDBC Use import java.sql.*; … Class.forName("oracle.jdbc.driver.OracleDriver"); System.setProperty("oracle.net.tns_admin", "G://Applications//Oracle//ADMIN"); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("Select LAST_NAME from PERSONS where ORG_UNIT like 'IT%'"); while (rset.next()) System.out.println(rset.getString("LAST_NAME")); rset.close(); stmt.close(); conn.close(); Load the Oracle JDBC driver Set which TNSNAMES file to use Create statement Specify the connection Execute query Obtain results Clean up The property can also be specified (or overridden) via the command line: java -Doracle.net.tns_admin=G:\Applications\Oracle\Admin … Oracle Tools and Bindings with languages

Use of Prepared Statements PreparedStatement stmt = conn.prepareStatement("Select LAST_NAME from PERSONS where ORG_UNIT = ? and FIRST_NAME = ?"); stmt.setString(1, "IT"); stmt.setString(2, "EVA"); ResultsSet rset = stmt.executeQuery(); Better performance (no query re-parsing) Protect from SQL injection Use whenever possible Oracle Tools and Bindings with languages

Calling PL/SQL from Java // Function CallableStatement stmt = conn.prepareCall("{?= call supervisor.team_leader(?, ?, ?)}"); // Procedure CallableStatement stmt2 = conn.prepareCall("{call supervisor.team_leader(?, ?, ?)}"); stmt.registerOutParameter(1, Types.NUMERIC); stmt.registerOutParameter(4, Types.VARCHAR); stmt.setInt(2, 123456); stmt.setDate(3, new java.sql.Date((new java.util.Date()).getTime())); stmt.execute(); System.out.println(stmt.getInt(1)); System.out.println(stmt.getString(4)); package supervisor function team_leader(institute in varchar, date in date, result out varchar) All OUT and INOUT parameters have to be registered Indices start from 1 In case of a function, the first parameter is the result Oracle Tools and Bindings with languages

conn.setAutoCommit(false/true); Commits and rollbacks conn.setAutoCommit(false/true); true - statements are committed individually false - statements are grouped until commit() or rollback() conn.commit(); Commit the current transaction and release DB locks conn.rollback(); Rollback (undo) the current transaction conn.rollback(savepoint); Undo the changes made after the given save point N.B. Auto-commit is switched ON by default Oracle Tools and Bindings with languages

Proper Exception Handling JDK 1.7 JDK < 1.7 try ( Connection conn = …; PreparedStatement stmt = … ; ResultSet rset = … ; ) { // Some database operations } catch (Exception e) { // Handle the exception (e.g. logging) Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { // Some database operations } catch (Exception e) // Handle the exception (e.g. logging) finally if (rset != null) rset.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(): IF NOT: Run out of connections Run out of database sessions May crash both yours and other apps running on the database Oracle Tools and Bindings with languages

JSP Example (using JSTL) <%@ page contentType="text/html;charset=windows-1252"%> <%@ taglib prefix="c" uri="/WEB-INF/tlds/c.tld"%> <%@ taglib prefix="sql" uri="/WEB-INF/tlds/sql.tld"%> <html> <body> <sql:query var="result" sql="Select FIRST_NAME, LAST_NAME from PERSONS where ORG_UNIT like 'IT%'" dataSource="jdbc:oracle:thin:FOUNDATION_PUB/XX@cerndb1"/> <table> <tr><th>First name</th><th>Last Name</th></tr> <c:forEach items="${result.rows}" var="row"> <tr><td>${row.FIRST_NAME}</td><td>${row.LAST_NAME}</td> </c:forEach> </table> </body> </html> JSP = Java Server Pages JSTL = JSP Standard Tag Library CERN Java Web Hosting: http://webservices.web.cern.ch/ Oracle Tools and Bindings with languages

Beyond simple JDBC javax.sql.* package DataSource, connection pooling, distributed transactions Lightweight connection pools (e.g. c3p0) Opening a connection is costly -> reuse! Use pooling for extensive DB use JDBC Abstraction Frameworks (e.g. Spring JDBC) Simplify use of JDBC Object Relational Mappers (e.g. Hibernate) Map Java objects to database tables Handle object relationships Save/load complex objects with a single command Oracle Tools and Bindings with languages

Further Information E-mail: Rostislav.Titov@cern.ch Oracle Database JDBC Developer's Guide and Reference: http://docs.oracle.com/cd/B28359_01/java.111/b31224/toc.htm Oracle Tools and Bindings with languages