Www.javacup.ir Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.

Slides:



Advertisements
Similar presentations
16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
Advertisements

Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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.
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
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 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
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.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
1 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Database applications with JDBC Jiafan Zhou. DBMS Database management systems (DBMS) is an organised collection of data. Usually database stores data.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
Databases: Queries with Java Dr Andy Evans. JDBC SQL Three methods: Statements: Standard, simple, SQL. PreparedStatements: Compiled SQL statements that.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui COMP 302 Database Systems Java Data Base Connectivity Lecturer Dr Pavle Mogin.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
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.
Java 7 Certification JDBC & Related Design Pattern NetCom’s Average Instructor Rating: 8.7/9 Arthur Gober Subject Matter Expert.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
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.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
1 Session 2 Module 3: Scrollable Resultset and Rowsets.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
JDBC™ Advanced Concepts
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Basics of JDBC.
JDBC (Java Database Connectivity)
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
1 JDBC – Java Database Connectivity CS , Spring 2010.
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.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC III IS Outline  Scrollable ResultSets  Updatable ResultSets  Prepared statements  Stored procedures.
JSP and DB.
CS3220 Web and Internet Programming Database Access with JDBC
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
UNIT-2 Java Database Programming
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
Bolat Azamat, Kim Dongmin
JDBC API.
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Sadegh Aliakbary

Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP is clearly noted as the source in the used case. JAVACUP shall not be liable for any errors in the content, or for any actions taken in reliance thereon. Please send your feedback to 2JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Agenda JDBC Connection Statement ResultSet Transaction RowSet 3JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC JDBC API provides a standard database – independent interface to interact with RDMSs. Typically, you use the JDBC API to connect to a database, query the data, and/or update data. Using JDBC API relieves you of the effort to learn specific syntaxes for different databases. Using JDBC API you write a query using standard SQL and the Java API processes the result in a database- independent manner. 4JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC The collection of implementation classes that is supplied by a vendor to interact with a specific database is called a ‘JDBC driver’. The ‘JDBC driver’ is used to connect to the RDMS. 5JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

The Architecture of JDBC 6JAVACUP.ir

Class.forName("com.mysql.jdbc.Driver"); String SQL = "SELECT * FROM classes"; try ( Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/cse3330a", "root", "aSecret123"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SQL) ) { while (rs.next()) { System.out.println(rs.getString("prof")); } JDBC Example JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source 7

JDBC To connect to a database: 1. Obtain the JDBC driver class files and add them to the CLASSPATH environment variable. 2. Register the JDBC driver with the ‘DriverManager’. 3. Construct a connection URL. 4. Use the static ‘getConnection()’ method of ‘DriverManager’ to establish a connection. 8JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC To connect to our APACHE DERBY database: // Register the JDBC driver class String driver="org.apache.derby.jdbc.EmbeddedDriver"; Class.forName(driver); // set up the database name String dbName="jdbcDemoDB"; // define the Derby connection URL to use String connectionURL = "jdbc:derby:" + dbName + ";create=true"; // establish the connection to the database. conn = DriverManager.getConnection(connectionURL); 9JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC You can execute different types of SQL statements using a JDBC driver. We use different JDBC ‘statement’ objects depending upon the kind of SQL statement. An instance of ‘java.sql.Statement’ interface represents a SQL statement in a java program. three interfaces to represent SQL statements: 1. Statement 2. Prepared Statement 3. Callable Statement 10JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC a ‘Statement’ object: SQL statement in the form of a string These SQL statements are compiled each time they are executed. ‘PreparedStatement’ object: pre-compile a SQL statement once and execute it multiple times Lets you specify a SQL statement in the form of a string that uses placeholders. You supply the values of the placeholders before executing the statement. ‘CallableStatement’ object: for a stored procedure or function in a database 11JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Statements 12JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC To execute a SQL statement using a ‘Statement’ object: 1. Get a connection object. Connection conn = … (get a Connection object) 2. Use the connection object to create a ‘Statement’ object: Statement stmt = conn.createStatement(); 13JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC 3. Set up your SQL in a string: String sql = “update person set income=income*1.1”; 4. Execute the statement by calling one of the ‘execute’ methods of the ‘Statement’ object: int rowsUpdated = stmt.executeUpdate(sql); 5. Close the ‘Statement’ object to release resources: stmt.close(); 6. Commit the transaction to the database: conn.commit(); 14JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

‘Statement’ interface ‘execute()’ method is used to execute a SQL statement which does not return a value, such as ‘CREATE TABLE’. ‘executeUpdate()’ method is used for SQL that updates a database, as in ‘INSERT’, ‘UPDATE’ and ‘DELETE’ SQL statements. It returns the number of rows affected. ‘executeQuery()’ is used for SQL that produces a resultset, as in ‘SELECT’ SQL statements. 15JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC the ‘auto-commit’ property for the ‘Connection’ object is set to ‘true’ by default. If a ‘Connection’ is not in auto-commit mode, you must call the ‘commit()’ or ‘rollback()’ method of the ‘Connection’ object to commit or rollback the transaction 16JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC try { Connection conn = get the connection… conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String sql = “update person set income=income*1.1”; int rowsUpdated = stmt.executeUpdate(sql); stmt.close(); conn.commit(); conn.close(); } catch (SQLException e) { conn.rollback(); e.printStackTrack(); conn.close();} 17JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

PreparedStatements String sql = “insert into person” + “person_id,first_name,last_name,gender,”+ ”values (?,?,?,?,?,?)”; PreparedStatement pstmt = conn.preparedStatement(sql); pstmt.setInt(1,801); 18JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Prepared Statements, Parameters String sql = “insert into person” + “person_id,first_name,last_name,gender,”+ ”values (?,?,?,?,?,?)”; Connection conn = get a connection object…; Prepared Statement pstmt = conn.prepareStatement(sql); pstmt.setInt(1,801); pstmt.setString(2,”Tom”); pstmt.setString(3,”Baker”); pstmt.setString(4,”M”); java.sql.Date dob = java.sql.Date.valueOf(“ ”); pstmt.setDate(5,dob); pstmt.setDouble(6,45900); pstmt.executeUpdate(); 19JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

ResultSet a ‘SELECT’ ‘ResultSet’. the data arranged in rows and columns. The ‘Statement’ or ‘PreparedStatement’ or ‘CallableStatement’ object returns the result of a query as a ‘ResultSet’ object 20JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC You can get information about the properties of a ‘ResultSet’ supported by a JDBC driver by using methods of the ‘DatabaseMetaData’ interface. First we get a ‘DatabaseMetaData’ object as follows: 1. Connection conn = get a connection…. 2. DatabaseMetaData dmd = conn.getMetaData (); 21JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC Some additional ‘DatabaseMetaData’ methods: String dbName = dmd.getDatabaseProductName(); String dbVersion = dmd.getDatabaseProductVersion(); String driverName = dmd.getDriverName(); String driverVersion = dmd.getDriverVersion(); 22JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC ResultSet rs = stmt.executeQuery(sql); While (rs.next()) { //process the current row in rs… } //done with the ResultSet rs. 23JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

ResultSet, get methods A ‘ResultSet’ object lets you read the value of a column from its current row using one of the ‘getXXX()’ methods, where ‘XXX’ is the data type of the column.(e.g. ‘getInt()’, ‘getString()’) You must specify the index of column name in the ‘getXXX()’ method whose value you want to read. int personID = rs.getInt(“person_id”); String firstName = rs.getString(2); 24JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC Connection conn = get a Connection object … Statement stmt = conn.getStatement(); String sql = “select person_id, first_name,”+ “last_name,dob,income from person”; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int personID=rs.getInt(1); String firstName=rs.getString(2); String lastName = rs.getString(3); java.sql.Date dob = rs.getDate(4); double income = rs.getDouble(5); //do something with the retrieved values from the cols. } 25JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC You can close a ‘ResultSet’ object by calling its ‘close()’ method. rs.close(); Closing the ‘ResultSet’ frees the resources associated with it. When the ‘Statement’ object that produces the ‘ResultSet’ object is closed, it automatically closes the ‘ResultSet’ object. 26JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

ResultSet Cursor Methods void beforeFirst() Sets the cursor just before the first row in the ResultSet. void afterLast() Sets the cursor just after the last row of the ResultSet. boolean absolute(int rowNumber) Sets the cursor to the requested row number absolutely. boolean relative(int rowNumber) Sets the cursor to the requested row number relatively. boolean next() Sets the cursor to the next row of the ResultSet. boolean previous() Sets the cursor to the previous row of the ResultSet 27JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC The interface ‘RowSet’ from the ‘javax.sql’ package is a wrapper for ‘ResultSet’ and inherits from the ‘ResultSet’ interface. A ‘RowSet’ allows for simpler JDBC programming. You need not deal directly with ‘Connection’ and ‘Statement’ objects, all you need to work with is the ‘RowSet’ object. 28JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC The ‘javax.sql.RowSet’ package defines five interfaces which inherit from the ‘RowSet’ interface Therefore, all the methods of the ‘ResultSet’ interface are available in these five types of rowsets. Typically, database vendors provide implementation classes for the five types of rowsets. 29JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC The five types of rowsets are: JdbcRowSet CachedRowSet WebRowSet FilteredRowSet JoinRowSet 30JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

31JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC try { RowSetFactory rsf = RowSetProvider.newFactory(); JdbcRowSet jrs = rsf.createJdbcRowSet(); //… work with the JdbcRowSet… } catch (SQLException e) { e.printStackTrace(); } 32JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC RowSet rs = … get a RowSet object … String sql=“select person_id,first_name”+ “last_name from person”; rs.setCommand(sql); 33JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC RowSet rs = … get a RowSet object … String sql=“select person_id,first_name”+ “last_name from person”+ “where income between ? and ?”; rs.setDouble(1, ); rs.setDouble(2, ); rs.setCommand(sql); 34JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

JDBC A ‘RowSet’ inherits all cursor movement methods from the ‘ResultSet’ interface. By default, all ‘RowSet’ objects are bi-directional scrollable and updateable. rs.execute(); while (rs.next()) { int personID = rs.getInt(“person_id”); String firstname=rs.getString(“first_name”); } 35JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

RowSet Example 36JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

DAO // Main.java public class Main { public static void main( String[] args) { Student student = new Student(... ); StudentDAO studentDAO = new OODBMSDAO(); studentDAO.insertStudent(student); } 37JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

StudentDAO // RDBMSDAO.java public class RDBMSDAO implements StudentDAO { public void insertStudent( Student student){ // insertStudent implementation } public Student findStudent( int id){ // findStudent implementation return Student; } public void deleteStudent( int id) { // deleteStudent implementation } 38JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

Further Readings DAO and Generic DAO patterns JDBC+Spring DataSource, RowMapper, JdbcTemplate, … ORM Hibernate CQRS Pattern Separate reporting db Datawarehousing NoSQL 39JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source

40JAVACUP.ir Contents redistribution is allowed if JAVACUP is noted as the source