CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API



Similar documents
Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

JDBC (Java / SQL Programming) CS 377: Database Systems

CS/CE 2336 Computer Science II

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Prof. Edwar Saliba Júnior

Using Netbeans and the Derby Database for Projects Contents

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.1

Tutorial for Spring DAO with JDBC

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

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

How To Use A Sas Server On A Java Computer Or A Java.Net Computer (Sas) On A Microsoft Microsoft Server (Sasa) On An Ipo (Sauge) Or A Microsas (Sask

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

The JAVA Way: JDBC and SQLJ

Introduction Web Portal Main Page Group Management Create group Modify Group Member List... 5

CS346: Database Programming.

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Overview of Web Services API

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration

Package sjdbc. R topics documented: February 20, 2015

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

LSINF1124 Projet de programmation

FileMaker 14. ODBC and JDBC Guide

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

Java and Microsoft Access SQL Tutorial

FileMaker 12. ODBC and JDBC Guide

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Microsoft SQL Server Features that can be used with the IBM i

Part IV: Java Database Programming

Installation of MSSQL Server 2005 Express Edition and Q-Monitor 3.x.x

FileMaker 11. ODBC and JDBC Guide

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

Implementing the Shop with EJB

Migrating helpdesk to a new server

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

Application note: Connecting the to a Database

FileMaker 13. ODBC and JDBC Guide

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

Installation of MSSQL Server 2008 Express Edition and Q-Monitor 3.x.x

Web Service Caching Using Command Cache

Upgrading MySQL from 32-bit to 64-bit

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

Implementing a Web Service Client using Java

Java DB Performance. Olav Sandstå Sun Microsystems, Trondheim, Norway Submission ID: 860

Getting Started using the SQuirreL SQL Client

Talend for Data Integration guide

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

Microsoft Dynamics GP

DEVELOPING MULTITHREADED DATABASE APPLICATION USING JAVA TOOLS AND ORACLE DATABASE MANAGEMENT SYSTEM IN INTRANET ENVIRONMENT

Querying Databases Using the DB Query and JDBC Query Nodes

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

1. Building Testing Environment

CSCI110 Exercise 4: Database - MySQL

Using the SQL TAS v4

Self-test Database application programming with JDBC

StoreGrid Backup Server With MySQL As Backend Database:

AWS Schema Conversion Tool. User Guide Version 1.0

CS170 Lab 11 Abstract Data Types & Objects

Create e-commerce website Opencart. Prepared by : Reth Chantharoth Facebook : rtharoth@yahoo.

HR Onboarding Solution

HELP DESK MANUAL INSTALLATION GUIDE

Secure Messaging Server Console... 2

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Docker Java Application with Solr, Mongo, & Cassandra: Design, Deployment, Service Discovery, and Management in Production

Installation of IBM DB2 9.1.x and Q-Monitor 3.x.x

Developing SQL and PL/SQL with JDeveloper

Security Module: SQL Injection

How To Let A Lecturer Know If Someone Is At A Lecture Or If They Are At A Guesthouse

DbSchema Tutorial with Introduction in SQL Databases

Java Access to Oracle CRM On Demand. By: Joerg Wallmueller Melbourne, Australia

public void setusername(string username) { this.username = username; } public void setname(string name) { this.name = name; }

Installation Guidelines (MySQL database & Archivists Toolkit client)

SFTP Server User Login Instructions. Open Internet explorer and enter the following url:

Online Backup Client User Manual

Online Backup Linux Client User Manual

2. Follow the installation directions and install the server on ccc

SQL and programming languages

Bitrix Site Manager ASP.NET. Installation Guide

Business Interaction Server. Configuration Guide Rev A

Database Access Through Java Technologies

Active Directory Authentication Integration

Version of this tutorial: 1.06a (this tutorial will going to evolve with versions of NWNX4)

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Brazil + JDBC Juin 2001, douin@cnam.fr

Transcription:

Introduction The JDBC API was designed to keep simple things simple. This means that the JDBC makes everyday database tasks easy. In this lab you will learn about how Java interacts with databases. JDBC helps you to write java applications that manage these three programming activities: Connect to a data source, like a database; Send queries and update statements to the database; Retrieve and process the results received from the database in answer to your query. In general, to process any SQL statement with JDBC, you follow these steps: 1. Establishing a connection. 2. Create a statement. 3. Execute the query. 4. Process the ResultSet object. 5. Close the connection Establishing Connections First, establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object. private Connection connection = DriverManager.getConnection( databaseurl, databaseusername, databasepassword ); Typically, a JDBC application connects to a target data source using two classes. One of them: DriverManager: this fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. Example of database URL: MySQL: jdbc:mysql://localhost:3306/, where localhost is the name of the server hosting your database, and 3306 is the port number. This method specifies the user name and password required to access the DBMS.

Creating Statements A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object. private Statement statement = connection.createstatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); Executing Queries To execute a query, call an execute method from Statement such as the following: execute: returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResutSet. executequery: returns one ResultSet object. executeupdate: returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements. private ResultSet resultset = statement.executequery( "SELECT * FROM smartphone WHERE manufacturer = '" + manufacturer + "'" ); Processing ResultSet Objects You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. You call various methods defined in the ResultSet object to move the cursor. resultset.next(); Moves the cursor forward by one row. Closing Connections When you are finished using a Statement, call the method Statement.close to immediately release the resources it is using. When you call this method, its ResultSet objects are closed.

statement.close(); Your task Read more about JDBC Basics: http://download.oracle.com/javase/tutorial/jdbc/basics/index.html Create a new table in your database Connect to your database with any SQL tool you like and execute the SQL script provided. Normally your database name starts with a year plus your username, for example: 2014_xx. You should know the password. Contact CS helpdesk if you can t connect. Get MySQL Connector/J 1. Create lab8 folder in your home directory on Windows. 2. Go to http://dev.mysql.com/downloads/connector/j/ 3. Download mysql connector java 5.1.15.zip ZIP archive. 4. Unzip it in your lab8 folder and rename folder to jconnector. Configure DrJava Open DrJava. Choose: Edit Preferences Resource Locations. Click Add. Select mysql connector java 5.1.15 bin.jar in your jconnector folder. Click OK. Writing Java classes 1. Create Catalog.java and Smartphone.java in your Lab8 folder. Compile both classes and run Catalog. 2. Explain what method Catalog.getManufacturer does and how? 3. Research and explain 3 types of ResultSet. 4. Research and explain 2 ResultSet concurrency levels. 5. Write method Catalog.setManufacturer (Smartphone smartphone). It receives a single Smartphone object as an argument and inserts it into database. Use ResultSet.insertRow() method. Submission A pdf document should be created detailing the answers to the questions above. This document is due by email to d.grigoras@cs.ucc.ie, subject: CS2506 lab8, at latest at the beginning of the next lab 15 th March. The header of the document should include the name and student id: Student name

UCC ID.. Lab results

Smartphone.java public class Smartphone { private String manufacturer; private String model; private String os; public Smartphone() { manufacturer = "None"; model = "None"; os = "None"; // Setters and Getters public void setmanufacturer( String manufacturer ) { this.manufacturer = manufacturer; public String getmanufacturer() { return manufacturer; public void setmodel( String model ) { this.model = model; public String getmodel() { return model; public void setos( String os ) { this.os = os; public String getos() { return os;

Catalog.java import java.sql.connection; import java.sql.drivermanager; import java.sql.statement; import java.sql.resultset; import java.sql.sqlexception; import java.util.arraylist; import java.util.iterator; public class Catalog { private String databaseusername = "<your_db_username>"; private String databasepassword = "<your_db_password>"; // database driver private String databasedriver = "com.mysql.jdbc.driver"; // database url private String databaseurl = "jdbc:mysql://localhost:3306/<name_of_your_database>"; private Connection connection = null; private Statement statement = null; private ResultSet resultset = null; public Catalog() { ArrayList< Smartphone > smartphonelist = new ArrayList< Smartphone >(); try { smartphonelist = getmanufacturer( "HTC" ); catch ( Exception e ) { e.printstacktrace(); System.exit( 1 ); // end catch Smartphone smartphone; //get an Iterator object for ArrayList using iterator() method.

Iterator itr = smartphonelist.iterator(); while( itr.hasnext() ) { smartphone = (Smartphone)itr.next(); System.out.println( smartphone.getmanufacturer() + " " + smartphone.getmodel() + " " + smartphone.getos() ); // end while // end catalog public ArrayList< Smartphone > getmanufacturer( String manufacturer ) throws Exception { ArrayList< Smartphone > smartphonelist = new ArrayList< Smartphone >(); // connect to database and query database try { // load database driver class Class.forName( databasedriver ); connection = DriverManager.getConnection( databaseurl, databaseusername, databasepassword ); statement = connection.createstatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); resultset = statement.executequery( "SELECT * FROM smartphone WHERE manufacturer = '" + manufacturer + "'" ); // get row data for ( int i = 0; resultset.next() && i < 10; i++ ) { Smartphone smartphone = new Smartphone(); smartphone.setmanufacturer( resultset.getstring( "manufacturer" ) ); smartphone.setmodel( resultset.getstring( "model" ) ); smartphone.setos( resultset.getstring( "os" ) ); // add to list smartphonelist.add( smartphone ); // end for

// end try /* if the DriverManager cannot connect to the database, method getconnection throws an exception */ catch( SQLException sqlexception ) { sqlexception.printstacktrace(); System.exit( 1 ); // end catch // if class loader cannot locate the driver class catch( ClassNotFoundException classnotfound ) { classnotfound.printstacktrace(); System.exit( 1 ); // end catch finally { statement.close(); connection.close(); return smartphonelist; // end finally // end method public static void main( String[] args ) { Catalog catalog = new Catalog(); // end main

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 SQL statement. Creates new table smartphone. USE `<name_of_your_database>` ; CREATE TABLE IF NOT EXISTS `<name_of_your_database>`.`smartphone` ( `id` INT NOT NULL AUTO_INCREMENT, `manufacturer` VARCHAR(500) NOT NULL, `model` VARCHAR(1000) NOT NULL, `os` VARCHAR(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB;