Chapter 10 Java and SQL. Wang Yang

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

Java Time Machine. Wang Yang

Accessing databases in Java using JDBC

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

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

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

信息检索与搜索引擎 Introduction to Information Retrieval GESC1007

Working with Databases and Java

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

数据库原理与应用 实验指导书 信息工程学院 2017 年 1 月

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

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

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

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

New Media Data Analytics and Application

New Media Data Analytics and Application

JAVA AND DATABASES. Summer 2018

AvalonMiner Raspberry Pi Configuration Guide. AvalonMiner 树莓派配置教程 AvalonMiner Raspberry Pi Configuration Guide

SQL and Java. Database Systems Lecture 20 Natasha Alechina

Lab # 9. Java to Database Connection

Programming in Java

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

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

SQL in a Server Environment

Java Database Connectivity

ICP Enablon User Manual Factory ICP Enablon 用户手册 工厂 Version th Jul 2012 版本 年 7 月 16 日. Content 内容

1. Spring 整合 Jdbc 进行持久层开发

计算机科学与技术专业本科培养计划. Undergraduate Program for Specialty in Computer Science & Technology

Application Notes for Ulane Tech PCS DataManager with Avaya Proactive Contact with PG230 Issue 1.0

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

第二小题 : 逻辑隔离 (10 分 ) OpenFlow Switch1 (PC-A/Netfpga) OpenFlow Switch2 (PC-B/Netfpga) ServerB PC-2. Switching Hub

Top 50 JDBC Interview Questions and Answers

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

JDBC Programming: Intro

A Benchmark For Stroke Extraction of Chinese Characters

Chapter 16: Databases

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Database Application Development

Chapter 1 An introduction to relational databases and SQL

Database Application Development

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

DB Programming. Database Systems

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

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

[ 电子书 ]Spark for Data Science PDF 下载 Spark 大数据博客 -

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

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

云计算入门 Introduction to Cloud Computing GESC1001

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1.

Introduction to Databases [p.3]

Understanding IO patterns of SSDs

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Web Applications and Database Connectivity using JDBC (Part II)

Database Application Development

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

CGS 3066: Spring 2017 SQL Reference

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

Unit 2 JDBC Programming

SQL DML and DB Applications, JDBC

三 依赖注入 (dependency injection) 的学习

实验三十三 DEIGRP 的配置 一 实验目的 二 应用环境 三 实验设备 四 实验拓扑 五 实验要求 六 实验步骤 1. 掌握 DEIGRP 的配置方法 2. 理解 DEIGRP 协议的工作过程

COMP102: Introduction to Databases, 23

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

基于项目信息类专业教育实验班本科培养计划 (2+2)

数据库系统概论讲义, 第 8 章编程 SQL,2015,3

UNIT-3 Java Database Client/Server

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

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

CSE 308. Database Issues. Goals. Separate the application code from the database

PERSİSTENCE OBJECT RELATİON MAPPİNG

学习沉淀成长分享 EIGRP. 红茶三杯 ( 朱 SIR) 微博 : Latest update:

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

智能终端与物联网应用 课程建设与实践. 邝坚 嵌入式系统与网络通信研究中心北京邮电大学计算机学院

王大珩 光电创新实验班本科培养计划. Undergraduate Program for Specialty in Opto-Information Science and Technology

Databases and SQL Lab EECS 448

如何查看 Cache Engine 缓存中有哪些网站 /URL

3dvia Composer Solidworks

Servlet 5.1 JDBC 5.2 JDBC

The Object-Oriented Paradigm. Employee Application Object. The Reality of DBMS. Employee Database Table. From Database to Application.

Visit for more.

系统生物学. (Systems Biology) 马彬广

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

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

Triangle - Delaunay Triangulator

Java E-Commerce Martin Cooke,

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

Application Programming for Relational Databases

Chapter 1 SQL and Data

Logging and Recovery. 444 Section, April 23, 2009

Networks and Web for Health Informatics (HINF 6220)

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

DB Programming. Database Systems, Presented by Rubi Boim

Machine Vision Market Analysis of 2015 Isabel Yang

Division of Science and Technology

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

CS143: Relational Model

Chapter 2: Relational Model

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

13 Creation and Manipulation of Tables and Databases

WEB SERVICES EXAMPLE 2

Transcription:

Chapter 10 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 for Table CourseInfo Query for all coursename Query for the number of course with studentcnt > 50 Query for CourseName, StudentCnt with course name containing 对象, and rank the result descending according to StudentCnt Insert into table a new record (any record will do) Modify 面向对象程序设计 1 课程的 studentcnt to 100 Delete all records related to 面向对象

SELECT CourseName FROM CourseInfo; SELECT count(*) FROM CourseInfo where StudentCnt > 50; SELECT CourseName, StudentCnt FROM CourseInfo where CourseName like "% 对象 %" order by StudentCnt DESC INSERT INTO CourseInfo (CourseName, StudentCnt, Semester) values (" 软件测试 ", 40, 第 一学期 ") UPDATE CourseInfo Set StudentCnt=100 where CourseName= 面向对象程序设计 1 DELETE from CourseInfo

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 String query = "INSERT INTO account (username, money, interest) VALUES (?,?,?)"; PreparedStatement pst = connection.preparestatement(query); pst.setstring(1, 张三 ); pst.setint(2, 100); pst.setint(3, 10); pst.addbatch(); pst.clearparameters(); pst.setstring(1, 李李四 ); pst.setint(2, 200); pst.setint(3, 20); pst.addbatch(); pst.clearparameters(); pst.executebatch(); pst.close();

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/