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

Similar documents
Java Database Connectivity (JDBC) 25.1 What is JDBC?

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

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

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

Accessing databases in Java using JDBC

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

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC

Java Database Connectivity

Working with Databases and Java

Unit 3 - Java Data Base Connectivity

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

Application Programming for Relational Databases

Logging and Recovery. 444 Section, April 23, 2009

Programming in Java

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

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

Lab # 9. Java to Database Connection

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

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

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

How to program applications. CS 2550 / Spring 2006 Principles of Database Systems. SQL is not enough. Roadmap

JDBC Programming: Intro

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

SQL from Applications

Databases 2012 Embedded SQL

13 Creation and Manipulation of Tables and Databases

Servlet 5.1 JDBC 5.2 JDBC

Visit for more.

INTRODUCTION TO JDBC - Revised spring

Instructor: Jinze Liu. Fall 2008

Overview. SQL from Applications. Accesing data from an application. Embedded SQL JDBC Stored Procedures. UVic C SC 370, Fall 2002

DATABASE DESIGN I - 1DL300

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018

Unit 2 JDBC Programming

SQL in a Server Environment

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

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

Non-interactive SQL. EECS Introduction to Database Management Systems

INTRODUCTION TO JDBC - Revised Spring

Chapter 16: Databases

Database Application Development

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

SQL and Java. Database Systems Lecture 20 Natasha Alechina

Chapter 10 Java and SQL. Wang Yang

CSE 135. Three-Tier Architecture. Applications Utilizing Databases. Browser. App. Server. Database. Server

JDBC, Transactions. Niklas Fors JDBC 1 / 38

C:/Users/zzaier/Documents/NetBeansProjects/WebApplication4/src/java/mainpackage/MainClass.java

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

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Database Lab#9 Connecting to postgresql database from java programs

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

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

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY

Databases CSCI 201 Principles of Software Development


UNIT-3 Java Database Client/Server

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

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

Database Application Programs PL/SQL, Java and the Web

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

Oracle Database 10g Java Web

Database connectivity (II)

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

O ne of the most important features of JavaServer

Introduction to Databases

Departamento de Lenguajes y Sistemas Informáticos

Web Applications and Database Connectivity using JDBC (Part II)

VanillaCore Walkthrough Part 1. Introduction to Database Systems DataLab CS, NTHU

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

JDBC 3.0. Java Database Connectivity. 1 Java

COMP102: Introduction to Databases, 23

Tiers (or layers) Separation of concerns

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

Database Application Development

Chapter 9 SQL in a server environment

Introduction to SQL & Database Application Development Using Java

Designing a Persistence Framework

DB I. 1 Dr. Ahmed ElShafee, Java course

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

JDBC Guide. RDM Server 8.2

Database Applications (15-415)

Oracle Exam 1z0-809 Java SE 8 Programmer II Version: 6.0 [ Total Questions: 128 ]

Chapter 1 An introduction to relational databases and SQL

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

SQream Connector JDBC SQream Technologies Version 2.9.3

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

DB Programming. Database Systems

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

Accessing a database from Java. Using JDBC

Introduction to Databases [p.3]

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

Chapter 9 SQL in a server environment

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

Ghislain Fourny. Information Systems for Engineers 7. The ecosystem around SQL

PERSİSTENCE OBJECT RELATİON MAPPİNG

Databases and SQL Lab EECS 448

Using OpenESQL to Map COBOL to DBMS Data Types

Pieter van den Hombergh. March 25, 2018

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

Real SQL Programming 1

Transcription:

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

OUTLINE Postgresql installation Introduction of JDBC Stored Procedure

POSTGRES INSTALLATION (1) Extract the source file Start the configuration (about one minute) Set up the prefix as the folder with your own permission Default would be home directory.

POSTGRES INSTALLATION (2) Compile all of your source code If the code was built correctly the last line would be Ready to install (less than one minute) Successfully install

POSTGRES INSTALLATION (3) Initialize database cluster Start the postgres server

OUTLINE Postgresql installation Introduction of JDBC Stored Procedure

JDBC Write once, Match all DBMS!! The Java Database connectivity Making a connection to a database Creating SQL or MySQL statements Executing queries in the database Viewing or Modifying the result records Oracle JDBC Driver Oracle Database Application JDBC Driver Interface SQL JDBC Driver MySQL JDBC Driver PostgreSQL JDBC Driver SQL Database MySQL Database PostgreSQL Database

STEPS OF CONNECTING DATABASE 1) Get the specific type of JDBC driver 2) Initializing the Driver 3) Start the Connection 4) Initialize one Statement object 5) Send out the SQL execute*() 6) Get the Resultset object which is returned by DBMS 7) Close the connection close()

(1) GET JDBC DRIVER Download driver from any DBMS company website Format: <DBMS_Name-JDBC-Type_n.jar> For example: postgresql-9.0-801.jdbc4.jar j Put it to any accessible library folder PostgreSQL JDBC Driver : http://jdbc.postgresql.org

(2) INITIALIZING THE DRIVER Importing JDBC Import java.sql.* Loading the server Class.forName("org.postgresql.Driver"); try { Class.forName("org.postgresql.Driver"); t l D i ") }catch(classnotfoundexception e) { System.out.println( Can t find Driver class "); }

(3) START THE CONNECTION String DRIVER = "org.postgresql.driver Driver"; String URL ="jdbc:postgresql://[ip]:5432/[db_name]"; String USER = "whoami"; String PASSWORD = "123456"; Connection conn = DriverManager.getConnection( getconnection( URL, USER, PASSWORD ); // DriverManager.getConnection( url ); System.out.println(conn.isReadOnly( ));... if ( conn!= null &&!conn.isclosed( ) ) { System.out.println( Successfully connect to database!"); } conn.close( );

(4) INITIALIZE ONE STATEMENT OBJECT AND (5)EXECUTE Statements stmt = conn.createstatement( ); ResultSet result = stmt.executequery( SELECT * FROM mytable ); Execute executequery() -> SQL for Searching and viewing executeupdate() -> SQL for Changing database s contents ExecuteQuery() Return results as row(s) () Use next() to move to next record, return a boolean value to indicate whether we have next record Use get<type>() to retrieve the data by attribute name or order

EXECUTE EXAMPLE Create / Update table Statements stmt = conn.createstatement( ); stmt.executeupdate( "CREATE TABLE jdemo ( title character varying(50),body text, id serial)"); stmt.executeupdate( ALTER TABLE jdemo ADD PRIMARY KEY (id) ); View data ResultSet result = stmt.executequery( executequery( SELECT * FROM jdemo ); while (result.next( )) { System.out.print(result.getInt( id ) + \t ); System.out.print(result.getString("title") + "\t"); System.out.println(result.getString("body")); i ( }

JDBC EXAMPLE 1. Import java.sql.*; 2. public class BasicResultSetExample { 2. public class BasicResultSetExample { 3. public static void main(string[] args) { 4. try{ 5. /** Loading the driver*/ 6. Class.forName(org.postgresql.Driver); 7. /** Getting Connection*/ 8. Connectioncon = DriverManager.getConnection(jdbc:postgresql://localhost:5432/test,root,root); 9. /** Creating Statement*/ 10. Statementstmt =con.createstatement(); 11 ResultSetrs=stmt executequery(select * from mytable); 11. ResultSetrs=stmt.executeQuery(select from mytable); 12. while(rs.next()) 13. { 14. System.out.print(Id is +rs.getint(id)); 15. System.out.println( Name is +rs.getstring(name)); 16 } 16. } 17. /** Closing the Connection*/ 18. stmt.close(); 19. con.close(); 20. }catch (Exceptione) { } ( p ){ 21. e.printstacktrace();} 22. } 23. }

OUTLINE Postgresql installation Introduction of JDBC Stored Procedure

WHAT ARE STORED PROCEDURES A stored procedure is an already written SQL statement that is saved in the database. Advantage Reduce roundtrips across the network Can make security easier to manage Are precompiled

STORED PROCEDURES - SQL How to run a stored procedures exec usp_displayallusers The SQL language inside the stored procedure SELECT * FROM USERLIST How to start with writing stored procedure A database management system A database built inside the database management system stem A text editor

FIRST STORED PROCEDURE /* Name: usp_displayallusers Description: displays all records and columns in USERLIST table Author: Tom O Neill Modification Log: Change Description Date Changed By Created procedure 7/15/2003 Tom O Neill */ CREATE PROCEDURE usp_displayallusers AS SELECT * FROM USERLIST

INPUT VARIABLES Input variables are essentially "storage" for data that you want to pass to your stored procedure. Global and local Declare at the top of the procedure Example @f_name @fullname @Homephone @ext

INSERT CREATE PROCEDURE usp_adduser @login varchar(20), @pswd varchar(20), @f_name varchar(25), @l_name varchar(35), @address_1 varchar(30), @address_2 varchar(30), @city varchar(30), @state char(2), @zipcode char(10), @email varchar(50) AS INSERT INTO USERLIST (login, pswd, f_name, l_name, address_1, address_2, city, state, zipcode, email) VALUES (@login, @pswd, @f_name, @l_name, @address_1, @address_2, @city, @state, @zipcode, @email) exec usp_adduser 'dnelson', 'dean2003', 'Dean', 'Nelson', '200 Berkeley Street', ' ', 'Boston', 'MA', '02116', 'dnelson@test.com'

UPDATE CREATE PROCEDURE usp_updateuser @usr_id int, @login varchar(20), @pswd varchar(20), @f_name varchar(25), @l_name varchar(35), @address_1 varchar(30), @address_2 varchar(30), @city varchar(30), @state char(2), @zipcode char(10), @email varchar(50) AS UPDATE USERLIST SET login=@login, pswd=@pswd, f_name=@f_name, l_name=@l_name, address_1=@address_1, address_2=@address_2, city=@city, state=@state, zipcode=@zipcode, email=@email WHERE usr_id=@usr_id exec usp adduser 1010,'dnelson', 'dean2003', 'Dean', 'Nelson', '200 Berkeley exec usp_adduser 1010, dnelson, dean2003, Dean, Nelson, 200 Berkeley Street', ' ', 'Boston', 'MA', '02116', 'dnelson@test.com'

PASS DATA TO A SELECT STORED PROCEDURE Steps Create header record Create stored procedure name and declare variables Create the rest of your stored procedure /* Name: usp_finduser Description: find a user Author: Tom O Neill Modification Log: Change Description Date Changed By Created procedure 7/15/2003 Tom O Neill */ */ exec usp_finduser 1 CREATE PROCEDURE usp_finduser @usr_id int AS SELECT * FROM USERLIST WHERE usr_id=@usr_id