Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
Introduction to XML CS348 Information System Guest Lecture Hazem Elmeleegy.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
19-Jun-15 SQL. SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell” is the only correct.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
1 Foundations of Software Design Lecture 27: Java Database Programming Marti Hearst Fall 2002.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 37 Java Database Programming.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Intro to JDBC To effectively use Java Data Base Connectivity we must understand: 1.Relational Database Management Systems (RDBMS) 2.JDBC Drivers 3.SQL.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Database Programming in Java Corresponds with Chapter 32, 33.
Views, Indexes and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Haiman Tian 1.
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
Database Environment Chapter 2 AIT632 Sungchul Hong.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
Georgia Institute of Technology Making Text for the Web part 5 Barb Ericson Georgia Institute of Technology March 2006.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 MySQL and JDBC.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
CSC 2720 Building Web Applications Database and SQL.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Index and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
Chapter 8 Databases.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
EXAMPLE I An application showing JDBC access to Cloudscape.
>> Introduction to MySQL. Introduction Structured Query Language (SQL) – Standard Database Language – Manage Data in a DBMS (Database Management System)
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 JDBC – Java Database Connectivity CS , Spring 2010.
In the Name Of Almighty Allah. Java Application Connection To Mysql Created by Hasibullah (Sahibzada) Kabul Computer Science Faculty Afghanistan.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
SQL CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Database Programming Basic JDBC Programming Concepts.
JDBC – Java Database Connectivity
JDBC.
Objectives In this lesson, you will learn about:
Interacting with Database
MSIS 655 Advanced Business Applications Programming
JDBC Example.
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Chapter 25 Databases

Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 2

Databases A database is a potentially large repository of data, organized for quick search and manipulation A database management system (DBMS) is software that interacts with the database Four primary operations: create, read, update, and delete (CRUD) There are several underlying ways to organize a database The most common type: a relational database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 3

Database Tables Two examples of database tables: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 4

Database Tables These tables are related using the locationID field One location can be associated with multiple people without duplicating data This saves space, reduces inconsistencies, and makes updates easier We can query the database (ask it a question) to determine things like – How many people live in Maple Glen? Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 5

Database Connections Before we can interact with a database in a Java program, we must first establish a connection The Java Database Connectivity (JDBC) API provides software to establish the connection In addition, we need software called a driver for the specific type of database used For example, if you're using a MySQL databse, you'll need an appropriate MySQL driver SQL (Structured Query Language) is a language for interacting with databases Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 6

import java.sql.*; /** * Demonstrates the establishment of a JDBC connector. * Java Foundations 4.0 */ public class DatabaseConnector { /** * Establishes the connection to the database and prints an * appropriate confirmation message. */ public static void main (String args[]) { try { Connection conn = null; // Loads the class object for the mysql driver into the DriverManager. Class.forName("com.mysql.jdbc.Driver"); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 7

// Attempt to establish a connection to the specified database via the // DriverManager conn = DriverManager.getConnection("jdbc:mysql://comtor.org/" + "javafoundations?user=jf2e&password=hirsch"); if (conn != null) { System.out.println("We have connected to our database!"); conn.close(); } } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 8

Creating Databases A SQL statement called CREATE TABLE can be used to add a new table to the database You specify the field names and sizes, among other things CREATE TABLE Student (student_ID INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (student_ID), firstName varchar(255), lastName varchar(255)) This establishes that the student_ID field will be the primary key, which must be unique Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25 - 9

Creating Databases To execute this statement from a Java program, you store it as a string and invoke the execute method of the Statement class (from the JDBC) String myCommand = "CREATE TABLE …"; Statement stmt = conn.createStatement(); boolean result = stmt.execute(myCommand); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Altering Tables The structure of a database table can be changed with the ALTER TABLE statement To add age and gpa fields to the Student table: ALTER TABLE Student ADD COLUMN (age tinyint UNSIGNED, gpa FLOAT (3,2) unsigned) To eliminate a field and remove all of its data: ALTER TABLE Student DROP COLUMN firstName Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Queries Data from a query is returned in a ResultSet object The SHOW COLUMNS statement returns the structure (a list of fields and their attributes) of a table ResultSet rSet = stmt.executeQuery("SHOW COLUMNS FROM Student"); We can extract meta data from the result set: ResultSetMetaData rsmd = rSet.getMetaData(); int numColumns = rsmd.getColumnCount(); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Queries The metadata for the Student table: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Inserting Data The INSERT command is used to add a row of data to a table It specifies the columns and their corresponding values: INSERT Student (lastName, age, gpa) VALUES ("Campbell", 19, 3.79) The studentID field is automatically incremented, and therefore not specified Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Inserting Data Some sample data for the Student class: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Retrieving Data The SELECT … FROM command is used to retrieve specific data from the database To get a list of all student's names and GPAs: SELECT lastName, gpa FROM Student A * can be used to get all fields The WHERE clause further specifies which data is sought: SELECT * FROM Student WHERE age >= 21 && gpa <= 3.0 Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Updating Data To update existing data in a table, we: – Obtain a ResultSet and navigate to the row(s) to update – Update the ResultSet value(s) – Update the database with the revised ResultSet ResultSet rSet = stmt.executeQuery("SELECT * FROM Student WHERE lastName = \"Jones\""); rSet.first() rSet.updateFloat("gpa", 3.41f); rSet.UpdateRow(); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.sql.*; /** * Demonstrates interaction between a Java program and a database. * Java Foundations 4.0 */ public class DatabaseModification { /** * Carries out various CRUD operations after establishing the * database connection. */ public static void main (String args[]) { Connection conn = null; try { // Loads the class object for the mysql driver into the DriverManager. Class.forName("com.mysql.jdbc.Driver"); // Attempt to establish a connection to the specified database via the // DriverManager conn = DriverManager.getConnection("jdbc:mysql://comtor.org/" + "javafoundations?user=jf2e&password=hirsch"); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

// Check the connection if (conn != null) { System.out.println("We have connected to our database!"); // Create the table and show the table structure Statement stmt = conn.createStatement(); boolean result = stmt.execute("CREATE TABLE Student " + " (student_ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " + " PRIMARY KEY (student_ID), lastName varchar(255), " + " age tinyint UNSIGNED, gpa FLOAT (3,2) unsigned)"); System.out.println("\tTable creation result: " + result); DatabaseModification.showColumns(conn); // Insert the data into the database and show the values in the table Statement stmt2 = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); int rowCount = stmt2.executeUpdate("INSERT Student " + "(lastName, age, gpa) VALUES (\"Campbell\", 19, 3.79)"); DatabaseModification.showValues(conn); // Close the database conn.close(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

} catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); } /** * Obtains and displays a ResultSet from the Student table. */ public static void showValues(Connection conn) { try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("SELECT * FROM Student"); DatabaseModification.showResults("Student", rset); } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Displays the structure of the Student table. */ public static void showColumns(Connection conn) { try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("SHOW COLUMNS FROM Student"); DatabaseModification.showResults("Student", rset); } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Displays the contents of the specified ResultSet. */ public static void showResults(String tableName, ResultSet rSet) { try { ResultSetMetaData rsmd = rSet.getMetaData(); int numColumns = rsmd.getColumnCount(); String resultString = null; if (numColumns > 0) { resultString = "\nTable: " + tableName + "\n" + "=======================================================\n"; for (int colNum = 1; colNum <= numColumns; colNum++) resultString += rsmd.getColumnLabel(colNum) + " "; } System.out.println(resultString); System.out.println( "======================================================="); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

while (rSet.next()) { resultString = ""; for (int colNum = 1; colNum <= numColumns; colNum++) { String column = rSet.getString(colNum); if (column != null) resultString += column + " "; } System.out.println(resultString + '\n' + " "); } } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); ex.printStackTrace(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Deleting Data To delete specific data from a table: DELETE FROM Student WHERE age >= 30 To delete an entire table: DROP TABLE Student Java Foundations, 3rd Edition, Lewis/DePasquale/Chase