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

Similar documents
Chapter 16: Databases

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

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Server-side Web Programming

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

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

Programming in Java

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

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

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

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

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Chapter 9 SQL in a server environment

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

Application Programming for Relational Databases

Unit 3 - Java Data Base Connectivity

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

Lab # 9. Java to Database Connection

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

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

Working with Databases and Java

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

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

Servlet 5.1 JDBC 5.2 JDBC

Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS)

SQL and Java. Database Systems Lecture 20 Natasha Alechina

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

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

13.1 Relational Databases (continued) 13.1 Relational Databases. - Logical model

13.1 Relational Databases

Accessing databases in Java using JDBC

UNIT-3 Java Database Client/Server

IBM -

Top 50 JDBC Interview Questions and Answers

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Real SQL Programming 1

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

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

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

Database-Connection Libraries. Java Database Connectivity PHP

JDBC [Java DataBase Connectivity]

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

SNS COLLEGE OF ENGINEERING, Coimbatore

PERSİSTENCE OBJECT RELATİON MAPPİNG

Introduction to SQL & Database Application Development Using Java

Database Design and Programming

UNIT III - JDBC Two Marks

Chapter 10 Java and SQL. Wang Yang

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Server-side Web Programming

JDBC - INTERVIEW QUESTIONS

Visit for more.

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

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

Database-Connection Libraries

Introduction to Databases

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

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

Web Applications and Database Connectivity using JDBC (Part II)

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

Database connectivity (I) ()

Databases and MySQL. COMP 342: Programming Methods. 16 September Databases and MySQL

SQL DML and DB Applications, JDBC

Type Java.sql.sqlexception Error Code 0 Sql State S1000

Chapter 9 SQL in a server environment

Non-interactive SQL. EECS Introduction to Database Management Systems

JAVA AND DATABASES. Summer 2018

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

Development Technologies. Agenda: phpmyadmin 2/20/2016. phpmyadmin MySQLi. Before you can put your data into a table, that table should exist.

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

JDBC Programming: Intro

SQL in a Server Environment

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Database connectivity (II)

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Asst.Prof.Eng. IOAN-GHEORGHE RAŢIU, PhD Asst.Prof. NICOLETA DAVID. George Bariţiu University, Braşov

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

CHAPTER 2 JDBC FUNDAMENTALS

13 Creation and Manipulation of Tables and Databases

CHAPTER 44. Java Stored Procedures

DB I. 1 Dr. Ahmed ElShafee, Java course

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

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

SQL functions fit into two broad categories: Data definition language Data manipulation language

Embedded SQL. Introduction

Embedded SQL. Davood Rafiei

O ne of the most important features of JavaServer

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

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Unit 2 JDBC Programming

Database Application Development

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

Configuring a JDBC Resource for MySQL in Metadata Manager

Java E-Commerce Martin Cooke,

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

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

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

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

Database Application Development

Transcription:

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

Introduction to Database Management Systems Storing data in traditional text or binary files has its limits well suited for applications that store only a small amount of data not practical for applications that must store a large amount of data simple operations become cumbersome and inefficient as data increases

Introduction to Database Management Systems A database management system (DBMS) is software that is specifically designed to work with large amounts of data in an efficient and organized manner Data is stored using the database management system Applications written in Java or other languages communicate with the DBMS rather than manipulate the data directly DBMS carries out instructions and sends the results back to the application

Introduction to Database Management Systems The Application sends a command to the DBMS The Application displays the result to the user The DBMS executes the command on the Data The DBMS sends the result back to the Application

JDBC JDBC stands for Java database connectivity It is the technology that makes communication possible between the Java application and DBMS The Java API contains numerous JDBC classes that allow your Java applications to interact with a DBMS

SQL SQL stands for structured query language A standard language for working with database management systems Not used as a general programming language Consists of several key words, used to construct statements known as queries Statements or queries are strings passed from the application to the DBMS using API method calls Serve as instructions for the DBMS to carry out operations on its data

Using a DBMS To use JDBC to work with a database you will need a DBMS Oracle Microsoft SQL Server DB2 MySQL Java DB

Tables, Rows, and Columns A database management system stores data in a database A database is organized into one or more tables Each table holds a collection of related data, organized into rows and columns Record: A row is a complete set of information about a single item, divided into columns Field: Each column is an individual piece of information about the item

Database Organization

Column Data Types Columns in a database are assigned an SQL data type SQL data types are generally compatible with Java data types

Primary Keys A primary key is a column that holds a unique value for each row in a database table A primary key can be the combination of several columns in a table For example, VIN in cars table

The SQL SELECT Statement The SELECT statement is used to retrieve the rows in a table SELECT Columns FROM Table Columns is one or more column names Table is a table name Example 1: Example 2: SELECT brand FROM cars SELECT VIN, brand, price FROM cars Multiple column names are separated with a comma Example 3: SELECT * FROM cars The * character can be used to retrieve all columns in the table

More About SQL Statements SQL statements are free form tabs, new lines, and spaces between key words are ignored SQL key words and table names are case insensitive Example: The following statements all work the same: SELECT * FROM cars SELECT * FROM cars select * from cars

Specifying Search Criteria with the WHERE clause The WHERE clause can be used with the SELECT statement to specify a search criteria SELECT Columns FROM Table WHERE Criteria Criteria is a conditional expression Example: SELECT * FROM cars WHERE Price > 7000 Only the rows that meet the search criteria are returned in the result set A result set is an object that contains the results of an SQL statement

Inserting Rows In SQL, the INSERT statement inserts a row into a table INSERT INTO TableName VALUES (Value1, Value2,...) TableName is the name of the database table Value1, Value2,... is a list of column values Example: INSERT INTO cars VALUES ( 3AE9K28734, Honda', Accord', 2009, 125434, 9000, Silver ) Strings are enclosed in single quotes Values appear in the same order as the columns in the table

Inserting Rows If column order is uncertain, the following general format can be used INSERT INTO TableName (ColumnName1, ColumnName2,...) VALUES (Value1, Value2,...) ColumnName1, ColumnName2,... is a list of column names Value1, Value2,... is a list of corresponding column values Keep in mind that primary key values must be unique For example, a duplicate VIN is not allowed in the Coffee table

Deleting Rows with the DELETE Statement In SQL, the DELETE statement deletes one or more rows in a table DELETE FROM Table WHERE Criteria Table is the table name Criteria is a conditional expression Example 1: DELETE FROM cars WHERE brand = Honda' Deletes a single row in the cars table where the brand name is Honda Warning! DELETE FROM cars Because this statement does not have a WHERE clause, it will delete every row in the cars table

Updating an Existing Row In SQL, the UPDATE statement changes the contents of an existing row in a table UPDATE Table SET Column = Value WHERE Criteria Table is a table name Column is a column name Value is the value to store in the column Criteria is a conditional expression Example: UPDATE cars SET price = 7000 WHERE VIN = B30948AC343K'

Connecting to the carmax Database The static DriverManager.getConnection method is used to get a connection to the database DriverManager.getConnection(DatabaseURL); General format of the simplest version: General format if a user name and a password are required: DriverManager.getConnection(DatabaseURL, Username, Password); Username is a string containing a valid username Password is a string containing a password DatabaseURL lists the protocol used to access the database

Connecting to the carmax Database DatabaseURL is a string known as a database URL URL stands for uniform resource locator A simple database URL has the following general format: protocol:subprotocol:databasename protocol is the database protocol value is jdbc when using JDBC subprotocol varies depending on the type of DBMS value is mysql when using mysql databasename is the name of the database Using Java DB, the URL for the CoffeeDB database is: jdbc:mysql://localhost:3306/carmax

Connecting to the carmax Database The DriverManager.getConnection method Searches for and loads a compatible JDBC driver for the database specified by the URL Returns a reference to a Connection object Should be saved in a variable, so it can be used later (more on this in a moment) Throws an SQLException if it fails to load a compatible JDBC driver Final String DB_URL = "jdbc:mysql://localhost:3306/carmax"; Connection conn = DriverManager.getConnection(DB_URL);

Example of JDBC connection import java.sql.*; // JDBC connection Class.forName("com.mysql.jdbc.Driver").newInstance(); String s1 = "jdbc:mysql://localhost:3306/carmax"; Connection connection = DriverManager.getConnection(s1,"root", yourpassword"); connection.close(); // assuming you correclty set the classpath for com.mysql.jdbc.drive // we are going to practice this in lab assignment

Class.forName("com.mysql.jdbc.Driver").newInstance(); The Class class is located in the java.lang package, so it is distributed with java, and imported automatically into every class. What the forname() method does, is just return the Class object for the paramater that was loaded by the class loader. The newinstance() method then returns a new instance of the class. So then what happens is you call Class.forName(...) it returns com.mysql.jdbc.driver.class. You then call newinstance() on that class which returns an instance of the class, whith no paramaters, so it's basically calling new com.mysql.jdbc.driver();

Passing an SQL Statement to the DBMS Once you have established a connection, you must get a reference to a Statement object before you can issue SQL statements to the DBMS A Statement object has an executequery method that returns a reference to a ResultSet object A ResultSet object contains the results of the query Example: Connection conn = DriverManager.getConnection(DB_URL); Statement stmt = conn.createstatement(); String sqlstatement = "SELECT brand FROM cars"; ResultSet result = stmt.executequery(sqlstatement);

Getting a Row from the ResultSet Object A ResultSet object has an internal cursor Points to a specific row in the ResultSet The row to which it points is the current row Initially positioned just before the first row Can be moved from row to row to examine all rows

Getting a Row from the ResultSet Object A ResultSet object s next method moves the cursor to the next row in the ResultSet result.next(); moves to first row in a newly created ResultSet moves to the next row each time it is called

Getting a Row from the ResultSet Object A ResultSet object s next method returns a Boolean value true if successfully moved to the next row false if there are no more rows A while loop can be used to move through all the rows of a newly created ResultSet while (result.next()) { // Process the current row. }

Getting Columns in a ResultSet Object You use one of the ResultSet object s get methods to retrieve the contents of a specific column in the current row. Can pass an argument for either the column number or the column name System.out.println(result.getString(1)); System.out.println(result.getString(2)); System.out.println(result.getString(3)); System.out.println(result.getString(4)); System.out.println(result.getString( vin")); System.out.println(result.getString( brand")); System.out.println(result.getString( model")); System.out.println(result.getInt( year"));

And other things ResultSetMetaData rsmd = result.getmetadata(); System.out.println(rsmd.getColumnCount()); Select * from cars where year IS NULL;