EXAMPLE I An application showing JDBC access to Cloudscape.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Introduction to JDBC Standard framework for dealing with tabular and generally, relational data SQL (Structured Query Language) is standardized language.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
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
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
Object-Oriented Enterprise Application Development Introduction to JDBC.
Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Views, Indexes and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Haiman Tian 1.
CSE 305 Theory of Database Tutorial on Connecting with Sybase from Java program and Developing GUI Jalal Mahmud, TA, CSE 305.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Index and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
JDBC. A Basic MySQL Tutorial MySQL is an open source database management software that helps users store, organize, and retrieve data. It is a very powerful.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
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.
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.
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.)
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.
Basics of JDBC.
Web Programming Assistant Professor Xiaozhong Liu
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 JDBC – Java Database Connectivity CS , Spring 2010.
1 Download current version of Tomcat from: g/tomcat/ g/tomcat/ Install it in: C:\Program Files\Apache.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
SQL pepper. Why SQL File I/O is a great deal of code Optimal file organization and indexing is critical and a great deal of code and theory implementation.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
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.
Database Programming Basic JDBC Programming Concepts.
CompSci 280 S Introduction to Software Development
ASP.NET Programming with C# and SQL Server First Edition
Java Access to RDB Relational databases (RDBs) dominate today, due to:
Lec - 14.
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Introduction to Server-Side Web Development using JSP and Databases
JDBC 15-Nov-18.
Mr. Harish Sharma Asst. Professor Dept. of CA & IT SGRRITS Dehradun
Interacting with Database
Bolat Azamat, Kim Dongmin
Using a Database with JDBC
JDBC Example.
Presentation transcript:

EXAMPLE I An application showing JDBC access to Cloudscape.

import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import com.ibm.db2j.drda.DB2jServer;

public class SimpleApp { /* the default framework is embedded*/ public String framework = "embedded"; public String driver = "com.ibm.db2j.jdbc.DB2jDriver"; public String protocol = "jdbc:db2j:"; public static void main (String[] args) { new SimpleApp().go( args); } void go (String args[]) { /* parse the arguments to determine which framework is desired*/ parseArguments( args); System.out.println ("SimpleApp starting in " + framework + " mode.");

try { /* The driver is installed by loading its class. In an embedded environment, this will start up Cloudscape, since it is not already running. */ Class.forName(driver).newInstance(); System.out.println ("Loaded the appropriate driver."); Connection conn = null; Properties props = new Properties(); props.put ("user", "user1"); props.put ("password", "user1"); /* The connection specifies create=true to cause the database to be created. To remove the database, remove the directory db2jDB and its contents. The directory db2jDB will be created under the directory that the system property db2j.system.home points to, or the current directory if db2j.system.home is not set. */

if (framework.equals ("embedded")) { conn = DriverManager.getConnection (protocol + "db2jDB;create=true", props); } else { // jccjdbc framework DB2jServer server = new DB2jServer(null); server.testConnection("db2jDB;create=true", null, null, "localhost", 1527); conn = DriverManager.getConnection(protocol + "//localhost:1527/db2jDB", props); } System.out.println ("Connected to and created database db2jDB"); conn.setAutoCommit(false); /* Creating a statement lets us issue commands against the connection. */

Statement s = conn.createStatement(); // We create a table, add a few rows, and update one. s.execute ("create table db2jDB(num int, addr varchar(40))"); System.out.println ("Created table db2jDB"); s.execute ("insert into db2jDB values (1956,'Webster St.')"); System.out.println ("Inserted 1956 Webster"); s.execute ("insert into db2jDB values (1910,'Union St.')"); System.out.println ("Inserted 1910 Union"); s.execute( "update db2jDB set num=180, addr='Grand Ave.' where num=1956"); System.out.println ("Updated 1956 Webster to 180 Grand"); s.execute( "update db2jDB set num=300, addr='Lakeshore Ave.' where num=180"); System.out.println ("Updated 180 Grand to 300 Lakeshore");

// We select the rows and verify the results. ResultSet rs = s.executeQuery ("SELECT num, addr FROM db2jDB ORDER BY num"); if (!rs.next()) throw new Exception ("Wrong number of rows"); if (rs.getInt(1)!=300) throw new Exception ("Wrong row returned"); if (!rs.next()) throw new Exception ("Wrong number of rows"); if (rs.getInt(1)!=1910) throw new Exception ("Wrong row returned") if (rs.next()) throw new Exception ("Wrong number of rows");

System.out.println ("Verified the rows"); s.execute ("drop table db2jDB"); System.out.println ("Dropped table db2jDB"); // We release the result and statement resource rs.close(); s.close(); System.out.println ("Closed result set and statement"); // We end the transaction and the connection. conn.commit(); conn.close(); System.out.println ("Committed transaction and closed connection");

/* In embedded mode, an application should shut down Cloudscape. If the application fails to shut down Cloudscape explicitly, the Cloudscape does not perform a checkpoint when the JVM shuts down, which means that the next connection will be slower. Explicitly shutting down Cloudscape with the URL is preferred. This style of shutdown will always throw an "exception". */ boolean gotSQLExc = false; if (framework.equals ("embedded")) { try { DriverManager.getConnection("jdbc:db2j:;shutdown=true"); } catch (SQLException se) { gotSQLExc = true; } if (!gotSQLExc) System.out.println ("Database did not shut down normally"); else System.out.println( "Database shut down normally"); }

catch (Throwable e) { System.out.println ("exception thrown:"); if (e instanceof SQLException) printSQLError( (SQLException) e); else e.printStackTrace(); } System.out.println ("SimpleApp finished"); } static void printSQLError (SQLException e) { while (e != null) { System.out.println (e.toString()) e = e.getNextException(); }

private void parseArguments(String[] args) { int length = args.length; for (int index = 0; index < length; index++) { if (args[index]. equalsIgnoreCase ("jccjdbcclient")) { framework = "jccjdbc"; driver = "com.ibm.db2.jcc.DB2Driver"; protocol = "jdbc:db2j:net:"; // localhost:1527 }

This program accomplishes the following tasks:  starts up the Cloudscape engine, if necessary  creates and connects to a database  creates a table  inserts data  updates data  selects data  drops a table  disconnects  shuts down Cloudscape, if necessary

Run in the Embedded Environment  The simplest Cloudscape environment.  The application starts up an instance of Cloudscape within the current JVM and shuts down the instance before it completes.  No network access is involved. In an embedded environment, only one application at a time can access a database.

New Files and Directories: after running the application  db2jDB (directory) The directory that makes up the db2jDB database.  We must not modify anything in this directory, or we will corrupt the database.  The directory was created when the application connected with Cloudscape, using the attribute create=true in the database connection URL.  The database name, db2jDB, was also set in the database connection URL.  db2jDB\log (directory) The directory that holds the database log for the db2jDB database.  db2jDB\seg0 (directory) The directory that holds the data for the db2jDB database.  db2jDB\service.properties An internal file that holds boot- time configuration parameters for the db2jDB database; do not edit.  db2j.LOG The log file with Cloudscape progress and error messages.

Setting Class Path for an Embedded Environment  Cloudscape provides a script to help us get started setting class path in %DB2J_INSTALL%bin  This script is called setCP and  comes for Windows environment with.bat  For users working in this environment, copying the commands in this file will help us get started setting the class path.

Running the Application in an Embedded Environment  Open a command window and change directory in which the application files are copied For example: C:\Cloudscape_5.1\bin  DB2J_INSTALL environment variable is set to the the directory we installed the Cloudscape software (C:\Cloudscape_5.1)  Run Cloudscape's utility for testing the class path for an embedded environment java com.ibm.db2j.tools.sysinfo -cp arguments or java com.ibm.db2j.tools.sysinfo -cp embedded SimpleApp.class

com.ibm.db2j.tools public class sysinfo extends java.lang.Object This class (sysinfo) displays system information to system out.  This class displays system information to system out. To run from the command-line, enter the following: java com.ibm.db2j.tools.sysinfo  Also available on this class are methods which allow us to determine the version of the code for the system without actually booting a database.  This is the Cloudscape version of the.jar files, not of our databases.

If the environment is set up correctly  The utility shows output indicating success.  It looks like the following: FOUND IN CLASS PATH: Cloudscape primary library (db2j.jar) Valid Cloudscape license (Cloudscape primary library, or for evaluation copies of the software only, license.jar) user-specified class (SimpleApp) SUCCESS: All Cloudscape-Related classes for embedded environment found in class path.

If something is missing from class path environment  The utility indicates what is missing  For example, if we neglected to add the directory containing the SimpleApp class to our class path, the utility would indicate as such: Testing for presence of Cloudscape-related libraries for embedded environment. FOUND IN CLASS PATH: Cloudscape primary library (db2j.jar) Valid Cloudscape license (Cloudscape primary library, or for evaluation copies of the software only, license.jar) NOT FOUND IN CLASS PATH: user-specified class (SimpleApp) (SimpleApp not found.)

If we have our environment set up correctly  we can execute the application from the same directory java SimpleApp  A successful run produces the following output: SimpleApp starting in embedded mode. Loaded the appropriate driver. Connected to and created database db2jDB Created table db2jDB Inserted 1956 Webster Inserted 1910 Union Updated 1956 Webster to 180 Grand Updated 180 Grand to 300 Lakeshore Verified the rows Dropped table db2jDB Closed result set and statement Committed transaction and closed connection Database shut down normally

create=true function  Creates the standard database specified within the database connection URL  Cloudscape system and then connects to it.  If the database cannot be created, the error appears in the error log and the connection attempt fails with an SQLException indicating that the database cannot be found.

EXAMPLE II An application showing JDBC access to MySQL

import java.sql.*; public class JdbcExam2 { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; try { Class.forName ("com.mysql.jdbc.Driver"). newInstance(); con = DriverManager.getConnection ("jdbc:mysql:///examples", "root", "secret"); st = con.createStatement(); rs = st. executeQuery ("SELECT user_id, first_name, last_name, country_code FROM users"); while (rs.next()) { int userId = rs.getInt(1); String firstName = rs.getString(2); String lastName = rs.getString(3); String countryCode = rs.getString(4); System.out.println(userId + ". " + lastName + ", " + firstName + " (" + countryCode + ")"); }

} catch (Exception e) { System.err.println ("Exception: " + e.getMessage()); } finally { try { if(rs != null) rs.close(); if(st != null) st.close(); if(con != null) con.close(); } catch (SQLException e) { }

Step by Step Explanations  We create 3 variables to hold Connection, Statement and ResultSet objects for us which we'll create later in a try/catch/finally block. Connection con = null; Statement st = null; ResultSet rs = null;  Then, we enter a try/catch/finally block.  Our data access code will reside in the try block  Exception notification code in the catch block  Code to close the connection in the finally block

Step by Step Explanations cont’d  First thing we do to display records is to obtain a connection to MySQL database  we do that my first loading it's JDBC (Connector/J) driver and then using DriverManager to obtain a connection to our "examples" database.  We might want to change the password from "secret" to whatever is our password for 'root' account. Class.forName ("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection ( "jdbc:mysql:///examples", "root", "secret");

Step by Step Explanations cont’d  Once we are connected, we create a new SQL Statement object. st = con.createStatement();  We then execute this statement to obtain a ResultSet which contains all the records from the "users" table and we do that by executing a SELECT SQL statement. rs = st.executeQuery("SELECT user_id, first_name, last_name, " + "country_code FROM users");

Step by Step Explanations cont’d  We then iterate through that ResultSet to obtain values for each field of the "users" table. We then print these values on the user console  In the finally block we close off our ResultSet, Statement and Connection objects. Finally:  Compile the example,  Before running the Java program, make sure that MySQL server is running  properly created and setup "examples" database and "users" table.  Now to run our Java program, execute following command at the command prompt from the folder