Databases 2012 Embedded SQL

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

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

Java Database Connectivity

JDBC 3.0. Java Database Connectivity. 1 Java

Java Database Connectivity

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

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

DATABASE DESIGN I - 1DL300

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

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

Database Application Development

Logging and Recovery. 444 Section, April 23, 2009

Java Database Connectivity

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

Database Application Development Part 2 - Chapter

Instructor: Jinze Liu. Fall 2008

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

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

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

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

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

Application Programming for Relational Databases

Java E-Commerce Martin Cooke,

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

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Introduction to Databases

Database connectivity (II)

SQream Connector JDBC SQream Technologies Version 2.9.3

Unit 2 JDBC Programming

INTRODUCTION TO JDBC - Revised Spring

Visit for more.

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Accessing databases in Java using JDBC

INTRODUCTION TO JDBC - Revised spring

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Database Application Development

Database Application Development

Database Application Development

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

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

DB I. 1 Dr. Ahmed ElShafee, Java course

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

JDBC Java Database Connectivity is a Java feature that lets you connect

O ne of the most important features of JavaServer

SQL in a Server Environment (ii)

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

Persistency Patterns. Repository and DAO

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

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

JDBC [Java DataBase Connectivity]

SQL in a Server Environment

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

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

Using IBM-Informix datatypes with IDS 10 and web application server Keshava Murthy, IBM Informix Development

13 Creation and Manipulation of Tables and Databases

UNIT-3 Java Database Client/Server

SQL Environment: Module Types. System Aspects of SQL. SQL Environment: Introduction. SQL Environment: Introduction. SQL Environment: Privileges

Sun Microsystems Inc. JDBC TM 2.1 API

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

JDBC Programming: Intro

JAVA AND DATABASES. Summer 2018

SQL and Java. Database Systems Lecture 20 Natasha Alechina

Non-interactive SQL. EECS Introduction to Database Management Systems

Unit 3 - Java Data Base Connectivity

Database Application Development

Database Application Development

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

Using Java JDBC with InterSystems IRIS

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

System Aspects of SQL

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

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

COMP 430 Intro. to Database Systems. SQL from application code

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

Chapter 5: Advanced SQL" Chapter 5: Advanced SQL"

Lecture 27 10/30/15. CMPSC431W: Database Management Systems. Instructor: Yu- San Lin

Database Application Programs PL/SQL, Java and the Web

JDBC - INTERVIEW QUESTIONS

while (rs.next()) { String[] temp_array = {"","",""}; int prodid = rs.getint(1); temp_array[0] = ""+prodid;

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

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

PERSİSTENCE OBJECT RELATİON MAPPİNG

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

Three-Tier Architecture

SQL DML and DB Applications, JDBC

DB Programming. Database Systems

Chapter 4 Application Programs and Object-Relational Capabilities

UNIT III - JDBC Two Marks

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

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

Servlet 5.1 JDBC 5.2 JDBC

Database Applications. SQL/PSM Embedded SQL JDBC

Contents. Introducing the course. Aim: to learn engineering of multi-tired web based systems. Road map of the course. Roadmap..

Accessing a database from Java. Using JDBC

Cập nhật ResultSet trong JDBC

Introduction to JDBC. Lecture 12

PARTIAL Final Exam Reference Packet

CSE 530A. DAOs and MVC. Washington University Fall 2012

Transcription:

Databases 2012 Christian S. Jensen Computer Science, Aarhus University

SQL is rarely written as ad-hoc queries using the generic SQL interface The typical scenario: client server database SQL is embedded in the server application code 2

Static vs. Dynamic SQL Static SQL syntactic extension of host language predefined and stored in the database typical use: monthly accounting statements checked in advance, efficient Dynamic SQL API in host language dynamically interpreted by the database typical use: web applications highly flexible JDBC for Java, works well with Hibernate 3

JDBC Java Database Connectivity A common Java framework for SQL databases java.sql.* Each vendor provides a driver class com.ibm.db2.jcc.db2driver oracle.jdc.driver.oracledriver com.microsoft.sqlserver.jdbc.sqlserverdriver com.mysql.jdbc.driver SQL statements are built as string expressions Results are accessed through a cursor 4

Running a JDBC Application Initialization load driver create connection java.sql.drivermanager java.sql.connection Processing generate SQL process results java.sql.statement java.sql.resultset Termination end connection release data structures java.sql.connection java.sql.statement 5

A Simple Example import java.sql.*; public class Test { public static void main(string args[]) { Connection con; } } try { String server = "localhost"; String port = "50000"; String url = "jdbc:mysql://"+server+":"+port+"/sample"; String userid = userid"; String password = password"; Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection(url, userid, password); Statement stmt = con.createstatement(); ResultSet rs = stmt.executequery("select * FROM Rooms"); while (rs.next()) System.out.println(rs.getString(1)+" "+rs.getstring(2)); stmt.close(); con.close(); } catch(exception e) { e.printstacktrace(); } Dreyer-201 12 Zuse-127 10 Shannon-164 30 Shannon-157 40 Shannon-159 38 Wiener-026 30 Hopper-334A 4 Ada-333 26 Turing-029 8 Turing-129 8 Turing-230 12 Turing-130 12 Turing-030 12 Stibitz-123 12 Hopper-334 4 Shannon-156 24 Stibitz-113 12 Undervisning 36 Store-Aud 152 Lille-Aud 70 Turing-014 26 Turing-229 8 D-01 25 D-02 18 D-03 18 Aud-D1 100 Aud-D2 100 Aud-D4 62 Aud-G1 85 Aud-G2 85 Kol-G3 22 Kol-G4 22 G-32 20 G-33 20 Aud-E 286 Aud-F 165... 6

Creating A Connection Load the appropriate driver class: Class.forName("com.mysql.jdbc.Driver"); Create a connection object: DriverManager.getConnection(url, userid, password); URL structure (for MySQL) jdbc:mysql://server:port/database the name of your own machine is localhost the standard port number is 50000 the name of the database is, e.g., SAMPLE 7

Simple SQL Statements Create a statement object: Statement stmt = con.createstatement(); The statement object is used many times stmt.executequery(" "); stmt.executeupdate(" "); And is finally closed stmt.close(); 8

Transactions Default auto-commits after every statement, change with con.setautocommit(false); con.commit(); con.rollback(); Transaction isolation levels con.settransactionisolation(level); Connection.TRANSACTION_READ_COMMITTED Connection.TRANSACTION_READ_UNCOMMITTED Connection.TRANSACTION_READ_REPEATABLE_READ Connection.TRANSACTION_SERIALIZABLE con.setreadonly(true); 9

Impedance Mismatch Java uses native types int, char[], String,... collection classes SQL uses tables CHAR(7), VARCHAR(20), FLOAT, DATE,... possibly huge amounts of data Not obvious how to translate tables into Java objects Results are instead accessed using cursors 10

Using Result Sets A ResultSet object manages a cursor on rows ResultSet rs = stmt.executequery("..."); while (rs.next()) {... } rs.close(); room capacity rs Turing-216 4 Ada-333 26 Aud-E 286 11

Navigating With Cursors A cursor can by default only move forward rs.next(); A Boolean result tells if the move was possible looks like an iterator object An ORDER BY clause determines the order 12

Reading With Cursors Column index or column name String room = rs.getstring(1); int capacity = rs.getint("capacity"); Different result types getstring(...) getint(...) java.sql.time time = gettime(...) Check for NULL wasnull() rs room Turing-216 4 Ada-333 26 Aud-E 286 capacity 13

Better Cursors A result set can be made scrollable and updatable stmt = createstatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rs.previous(); rs.first(); rs.last(); rs.absolute(42); 14

Modifications with Cursors A result set can then be updated rs.updatestring("room","ada-333"); Updates can be pushed to the database rs.updaterow(); Rows can be deleted both places rs.deleterow(); room capacity rs Turing-216 4 ADA-333 26 Ada-333 26 Aud-E 286 15

Insertions With Cursors A special virtual insert row exists rs.movetoinsertrow(); rs.updatestring("room,"turing-310"); rs.updateint("capacity",4); rs.insertrow(); rs.movetocurrentrow(); room capacity rs Turing-216 4 Ada-333 26 Aud-E 286 Turing-310 4 16

Prepared Statements SQL statements may be prepared checked and compiled once executed multiple times PreparedStatement pstmt = con.preparestatement( ); "SELECT * FROM Rooms" ResultSet rs = pstmt.executequery(); 17

Arguments to Prepared Statements Use? symbols for variables Insert values using absolute position PreparedStatement pstmt = con.preparestatement( "INSERT INTO Meetings VALUES(?,?,?,'dDB',?)" ); pstmt.setint(1,34716); pstmt.setdate(2,new java.sql.date(2010,8,23)); pstmt.setint(3,14); pstmt.setstring(4,"csj"); pstmt.executeupdate(); 18

Metadata java.sql.resultsetmetadata reflectively describes the structure of a result names and types of columns allows generic queries java.sql.databasemetadata reflectively describes the structure of a database name, version, tables, supported SQL types allows generic connections 19

Result Set Metadata rs = stmt.executequery("select * FROM Rooms"); ResultSetMetaData rsm = rs.getmetadata(); int columns = rsm.getcolumncount(); for (int i=1; i<=columns; i++) { System.out.println( "Column "+i+" "+ "has name "+rsm.getcolumnname(i)+", " "SQL type "+rsm.getcolumntype(i)+" and " "JDBC type "+rsm.getcolumntypename(i) ); } Column 1 has name ROOM, SQL type 12 and JDBC type VARCHAR Column 2 has name CAPACITY, SQL type 4 and JDBC type INTEGER 20

SQL Injection Attacks Be careful with dynamic SQL: "SELECT * FROM Users WHERE userid ='" + userid + "'" Fine if userid is "mis" Bad if userid is "x' OR 'y'='y" all data is revealed Worse if userid is x';drop TABLE Users;--" all data is deleted Prepared statements avoid this problem 21

SQL Injection Cartoon 22