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

Similar documents
Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

SQL and Java. Database Systems Lecture 19 Natasha Alechina

LSINF1124 Projet de programmation

The JAVA Way: JDBC and SQLJ

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

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

SQL. Short introduction

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

CS/CE 2336 Computer Science II

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

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

Databases in Engineering / Lab-1 (MS-Access/SQL)

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

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

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

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

Self-test Database application programming with JDBC

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

Database Query 1: SQL Basics

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

A Brief Introduction to MySQL

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

Database Access Through Java Technologies

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

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

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

Database Systems. S. Adams. Dilbert. Available: Hans-Petter Halvorsen, M.Sc.

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

Using Netbeans and the Derby Database for Projects Contents

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

1 SQL Data Types and Schemas

Database Design and Programming

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

Brazil + JDBC Juin 2001, douin@cnam.fr

Java and RDBMS. Married with issues. Database constraints

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

Accesssing External Databases From ILE RPG (with help from Java)

Performance Tuning for the JDBC TM API

How To Create A Table In Sql (Ahem)

Financial Data Access with SQL, Excel & VBA

- Eliminating redundant data - Ensuring data dependencies makes sense. ie:- data is stored logically

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Database Administration with MySQL

DBMS SQL JDBC 1. Integrated data

Package sjdbc. R topics documented: February 20, 2015

Programming Database lectures for mathema

Relational databases and SQL

Procedural Extension to SQL using Triggers. SS Chung

Lab 2: PostgreSQL Tutorial II: Command Line

A basic create statement for a simple student table would look like the following.

Linas Virbalas Continuent, Inc.

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

Oracle to MySQL Migration

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

SQL Tables, Keys, Views, Indexes

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

High-Performance Oracle: Proven Methods for Achieving Optimum Performance and Availability

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components

How to Improve Database Connectivity With the Data Tools Platform. John Graham (Sybase Data Tooling) Brian Payton (IBM Information Management)

Applets, RMI, JDBC Exam Review

Apéndice C: Código Fuente del Programa DBConnection.java

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

Java DataBase Connectivity (JDBC)

SQL and programming languages

Chapter 1 JDBC: Databases The Java Way! What Is The JDBC? The JDBC Structure ODBC s Part In The JDBC Summary

What is a database? COSC 304 Introduction to Database Systems. Database Introduction. Example Problem. Databases in the Real-World

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Making Oracle and JDBC Work For You

IT2305 Database Systems I (Compulsory)

14 Triggers / Embedded SQL

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Intro to Databases. ACM Webmonkeys 2011

Java Server Pages and Java Beans

Part 2 - The Database Environment

Using Temporary Tables to Improve Performance for SQL Data Services

DBMS / Business Intelligence, SQL Server

Introduction to Triggers using SQL

Fundamentals of Database Design

Introduction to Database. Systems HANS- PETTER HALVORSEN,

MySQL Command Syntax

3.GETTING STARTED WITH ORACLE8i

IT2304: Database Systems 1 (DBS 1)

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Database Application Development. Overview. SQL in Application Code. Chapter 6

Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)

How I hacked PacketStorm ( )

Driver for JDBC Implementation Guide

Java MySQL Connector & Connection Pool

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

Transcription:

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

Outline Concern Data - File & IO vs. Database &SQL Database & SQL How Connect Java to SQL - Java Model for Database Java Database Connectivity (JDBC) - API

Concern Data File & IO vs. Database & SQL

Review of File & IO Experiment : Write Student Information into File 姓 名 学 号 成 绩 张 小 灵 71101101 89 李 小 乐 71101102 90 We can use two methods OutputStream Writer

Review of File & IO OutputStream 0000000 e5 bc a0 e5 b0 8f e7 81 b5 04 3c ea ad 00 00 00 0000010 59 e6 9d 8e e5 b0 8f e4 b9 90 04 3c ea ae 00 00 0000020 00 5a

Review of File & IO But if we want to change content read all the record change the specific record write all the record back rewrite All the record just for one record change

Review of File & IO We can use RandomAccessFile use seek() to specific position override the record change 张 小 灵 score to 91

Review of File & IO But if we want to change record length change 张 小 灵 name to 张 灵 what we get is 张 灵? 0000000 e5 bc a0 e7 81 b5 e7 81 b5 0000009 04 3c ea ad 00 00 00 59

Review of File & IO If multiple people want to modify the file at the same time we must use synchronization the process If Someone insert wrong data, like -1 for score we must write code to insure it will not be written if we want to use another language we must learn different data type and process

What we concern is Data We only want write Student Information into a table like excel, can easily manipulate the data we only concern data, not the media, : binaryfile, TextFile, CSVFile, Excel, not the process OutputStream, Writer, RandomAccessFile, not the programming language Java, C, C++,

What we concern is Data We want to create a table struct to describe data 姓 名 : String:2 ~10 Character 学 号 : String :7Character,All Numeric 成 绩 : Int : 0 ~100

What we concern is Data we want to manipulate data insert data record update data record delete data record query data record

What we concern is Data We want there are a common system to store data Database we want to learn only a common language to process it - SQL

Database & SQL

Basic Concepts in Database Database and DBMS RDBMS ( 关 系 型 数 据 库 管 理 系 统 ) Store data in rows and columns Rows called Record ( 记 录 ), and columns called Field ( 字 段 ) A set of rows and columns are called Table ( 表 ) A table usually represents an Entity ( 实 体 ) There are Relations ( 关 系 ) between Entities, ER Map Query through SQL( 结 构 化 查 询 语 言)

Basic Concepts in Database Application Users Application Programs Database Management System (DBMS) System Users database

Basic Concepts in Database Usual RDBMS MySQL / PostgreSQL / Berkeley DB Oracle SQL Server DB2

Basic Concepts in Database

Basic Concepts in SQL Structured Query Language SQL including DDL Data Definition Language These queries are used to create database objects such as tables, indexes, procedures, constraints Create, drop, alter,truncate,comment,rename DML Data Manipulation Language These queries are used to manipulate the data in the database tables. Insert, update, delete, select (more available) DCL Data Control Language These are data control queries like grant and revoke permissions

CRUD Operations in SQL CRUD means Create, Read, Update, Delete Create : create the table and insert data into table Read : select data from table Update : update data in the table Delete : delete data from the table

Create Statement Data Query! result create table Course ( StudentName varchar(10), StudentID char(7), CourseName varchar(10), score integer, primary key (studentid));

Insert Statement Data! ColumnName StudentName StudentID Score DataType varchar(10) char(7) int Query! INSERT into Course (StudentName, StudentID, Score) VALUES ( 张 小 灵, 7110101, 91) ; result

Insert Statement First assign which fields you want to insert you can just insert one field or two fields other fields will be null or default value Then you give values for the fields String must be quoted don t use Chinese or Chinese ()

Select Statement Data! Query! SELECT StudentName, Score FROM Course; Result

Select Where Condition Data! Query SELECT StudentName, Score FROM Course! Where Score > 90; Result

Select Where Combined Condition Data! Query SELECT StudentName, Score FROM Course! Where Score > 90 and StudentID < 7110103 ; Result

Select Where In Data! Query SELECT StudentName, Score FROM Course! Where StudentName in ( 张 小 灵, 李 小 乐 ); Result

Select Where Between Data! Query! SELECT StudentName, Score FROM Course Where SutdentID between 7110101 and 7110103 ; Result

Select Where Like Data! Query SELECT StudentName, Score FROM Course! Where StudentName Like 张 % ; Result

Select Where Order by Data! Query SELECT StudentName, Score FROM Course! Order by Score DESC; Result

Select Distinct Data! Query! SELECT Distinct(Score) FROM Course; Result

Select Where Count Data! Query! SELECT Count (Distinct(Score)) FROM Course; Result

Update Statement Data! Query UPDATE Course SET Score=95 Where! StudentID= 7110102 ; Result

Delete Statement Data! Query! DELETE FROM Course Where Score>91; Result

TEST Write following SQL query Query for all coursename Query for the number of course with studentcnt > 50 Query for sales of stores with name containing 对 象, and rank the result descending according to sales Insert into table a new record (any record will do) Modify 面 向 对 象 程 序 设 计 1 课 程 的 studentcnt to 100 Delete all records related to 面 向 对 象

TEST

How Connect Java to SQL Java Model for Database

JDBC JDBC - Java Database Connectivity Provides API for database access JDBC Client JSP/Servlet JDBC DB Server Client App Server DB Server

JDBC Principle Java APPs JDBC API JDBC Driver Manager JDBC Driver JDBC Driver JDBC ODBC Sql Server Oracle MySQL

JDBC Principle Connection 2 Client 3 Statement ResultSet 4 DB Server DriverManager 1

Java Database Connectivity API

JDBC API Provider: Sun Package java.sql javax.sql Major Classes and Interfaces DriverManager Class Connection Interface Statement Interface ResultSet Interface

Establish a Connection import java.sql.*;! Load the vendor specific driver Class.forName("com.mysql.jdbc.Driver");! Dynamically loads a driver class, for Mysql database Make the connection String dburl = "jdbc:mysql://localhost:3306/" +!! "MyDB?user=your_username&password=your_password";! Connection connection = DriverManager.getConnection(dbURL);! Establishes connection to database by obtaining a Connection object

Create JDBC statement(s) String query = Select * From Course ;! Statement stmt = conn.createstatement() ; Creates a Statement object for sending SQL statements to the database

execute and get Result ResultSet rs = stmt.executequery(query);! while (rs.next()) {!! System.out.println(rs.getString("StudentName"));! } 张 小 灵! 李 小 乐! 王 小 天! 赵 小 宝

Close all the resource rs.close();! stmt.close();! conn.close();! release all the resources of ResultSet, Statement, and Connection

JDBC Process try{ // 加 载 及 注 册 JDBC 驱 动 程 序 Class.forName(...); // 创 建 JDBC 连 接 Connection connection =... // 创 建 Statement Statement statement =... // 创 建 查 询 并 处 理 查 询 结 果 ResultSet rs =... } catch (ClassNotFoundException e) {System.out.println(" 无 法 找 到 驱 动 类 ");} catch (SQLException e) {e.printstacktrace();} finally { try { rs.close(); statement.close(); connection.close(); } catch (Exception e) { e.printstacktrace();} }

Two Way of Executing Statement executeupdate For queries with no results returned, usually Insert \ Delete \ Update executequery For queries with results returned, usually Select

PreparedStatement Interface Derived from Statement interface For repeatedly executed SQL Usually for queries with no result, such as Insert \ Delete \ Update Together with addbatch() and executebatch()

PreparedStatement Interface

Reference W3C School SQL 教 程 http://www.w3school.com.cn/sql/ SQL 语 句 教 程 http://www.1keydata.com/cn/sql/sql.php JDBC Data Access API JDBC Technology Homepage http://www.oracle.com/technetwork/java/javase/jdbc/index.html JDBC Database Access The Java Tutorial http://docs.oracle.com/javase/tutorial/jdbc/index.html JDBC Documentation http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/