Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.

Slides:



Advertisements
Similar presentations
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 PostgreSQL JDBC interface documentation
Advertisements

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.
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
1 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
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. –
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
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.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
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.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Copyright © 2002 ProsoftTraining. All rights reserved. Building Database Client Applications Using JDBC 2.0.
Web Design & Development 1 Lec Web Design & Development 2 More on JDBC.
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.
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 CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
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.
JDBC (Java Database Connectivity)
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
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.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JSP and DB.
CompSci 280 S Introduction to Software Development
JDBC and OCCI 10/29/2017.
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
Lec - 14.
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
JDBC.
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
JDBC – Java Database Connectivity
Using a Database with JDBC
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Basic JDBC Celsina Bignoli

What is JDBC Industry standard for database- connectivity between the Java language and a wide range of databases Generic Leverage existing database APIs Simple

JDBC Architecture Sybase DB Java Application DriverManager Sybase DriverMySQL DriverOracle Driver MySQL DB Oracle DB

JDBC Drivers Vendor-specific implementation of the JDBC interfaces Transparent to the database application developers

JDBC specifications JDBC 2.0 Core API (java.sql package) Scrollable ResultSets Streams JDBC 2.0 Standard Extension API (javax.sql package) DataSource Connection pooling Distributed transactions Rowsets JDBC 2.0 Specification JDBC 1.0 Specification Basic database connectivity

Loading the Driver Class.forName(driverClassName).newInstance(); Class.forName(“com.mysql.jdbc.Driver”).newInstance(); dynamically load a java class at runtime executes newInstance() to create an object of class Driver calling the default constructor for the class. The constructor executes code to register the class with the DriverManager

Connecting to the Database Connection DriverManager.getConnection(String url); DriverManager.getConnection( “jdbc:mysql://localhost/accounts?user=ro ot&password=cis384“);

URL URL: : : jdbc mysql //localhost/accounts : // [: ][/ ] //localhost/accounts // /prod //db.mycompany.com/prod //db.mycompany.com:4544/prod when not specified, connector/J will default to port 3306.

DriverManager -getConnection() method static Connection getConnection(String url) Attempts to establish a connection to the given database URL. static Connection getConnection(String url, Properties info) Attempts to establish a connection to the given database URL using the specified properties. static Connection getConnection(String url, String user, String password) Attempts to establish a connection to the given database URL as used identified by password.

getConnection() – Example Properties info = new Properties(); info.setProperty(“user”, “username”); info setProperty(“password”, “pwd”); Connection con = DriverManager.getConnection(url, prop); OR String username=“username”; String password=“password”; Connection con = DriverManager.getConnection(url, username, password);

Queries – Statement Object used to send a SQL statement to the database executes the SQL statement returns back the results of the SQL statement

createStatement() StatementcreateStatement () Creates a Statement object for sending SQL statements to the database.

executeQuery() ResultSetexecuteQuery(String sql) Executes the given SQL statement, which returns a single ResultSet object no assumption is made on the validity of the query if the SQL execute successfully it returns a ResultSet object containing rows from the database if the SQL fails it will raise a SQLException

Executing a Statement - Example ResultSet rs = stmt.executeStatement(“select name from pets”); ResultSet: Fluffy Claws Buffy Fang Chirpy Whistler Slim Puffball Initial cursor position next()

ResultSet Object A table of data representing a database result set maintains a cursor pointing to its current row of data Initially the cursor is positioned before the first row The next() method moves the cursor to the next row next() returns false when there are no more rows in the ResultSet object A default ResultSet object is not updatable and has a cursor that moves forward only

Moving Through the ResultSet - Example while (rs.next()) { System.out.println(rs.getString((1))); } Fluffy Claws Buffy Fang Chirpy Whistler Slim Puffball

Basic Getter Methods int getInt(int columnIndex) int getInt(String columnName) String getString(int columnIndex) String getString(String columnName) Date getDate(int columnIndex) Date getDate(String columnName)

Handling Errors Connector/J Driver throws a SQLException –errors connecting with the database –errors executing SQL statements To know more about a single Exception use the SQLException methods –getMessage() –getSQLState() –getErrorCode()

executeUpdate() method intexecuteUpdate (String sql) Creates a Statement object for sending SQL statements to the database. Returns either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing

Inserting a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“INSERT INTO pet VALUES(12, ’minou’, ’Gwen’, ’cat’)”);

Updating a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“UPDATE pet SET owner=‘Lucy’ where owner= ‘Gwen’ ”);

Deleting a Row - Example Statement stmt = connection.createStatement(); int i= stmt.executeUpdate(“DELETE FROM pet WHERE owner= ‘Gwen’ ”);

Prepared Statements - SQL ability to set up a statement once, and then execute it many times with different parameters. replace building ad hoc query strings, and do so in a more efficient manner. First implemented in the C API Available in Connector/J server-side starting from version 3.1

How databases execute queries parse the query invoke the optimizer to determine best query execution plan caches the plan – query is the key to fetch plan from cache

Prepared Statement - Example PREPARE sel_stmt FROM “SELECT name FROM pet WHERE id=?”; EXECUTE sel_stmt name Fluffy

JDBC – Dynamic Query Example Statement stmt = con.createStatement(); for int(i=1; i<=10; i++){ String stmtString = “select name from pet where id = “ +I; ResultSet rs = stmt.executeQuery(stmtString); while (rs.next()){ System.out.println(rs.getString(1)); } rs.close() } statement is parsed by the database each time new query plan is created for each select statement and cached (entire stmt being the key)

JDBC – PreparedStatement PreparedStatement ps = con.prepareStatement( “select name from pet where id =?“ ); for int(i=1; i<=10; i++){ ps.setInt(1, i); -- variable binding ResultSet rs = ps.executeQuery(); while (rs.next()){ System.out.println(rs.getString(1)); } rs.close(); } ? is called placeholder query is parsed only once and only 1 execution plan is created and caches for it executed many times after binding variables MUCH MORE EFFICIENT!

Placeholders- Setter methods voidsetInt(int parameterIndex, int value) voidsetString(int parameterIndex, String value) voidsetDate(int parameterIndex, java.sql.Date value) voidsetTimestamp(int parameterIndex, java.sql.Timestamp value) voidsetLong(int parameterIndex, long value)

Disconnecting from the database close a connection to the database to release resources Make sure you first close all component that use that connection Close components in the reverse order you opened them. rs.close() stmt.close() conn.close()