SlideShare una empresa de Scribd logo
1 de 21
CS178 Database Management
          “JDBC”
What is JDBC ?
• JDBC stands for “Java DataBase
  Connectivity”
• The standard interface for communication
  between a Java application and a SQL
  database
• Allows a Java program to issue SQL
  statements and process the results.
JDBC Classes and Interfaces
Steps to using a database query:
• Load a JDBC “driver”
• Connect to the data source
• Send/execute SQL statements
• Process the results
JDBC Driver
• Acts as the gateway to a database
• Not actually a “driver”, just a .jar file
  Java application                    Database Server


                        JDBC Driver
JDBC Driver Installation
• Must download the driver, copy it to
  cobweb then add the .jar file to your
  $CLASSPATH
• To set up your classpath, ssh into cobweb
  and execute the following command:
  – export CLASSPATH=$CLASSPATH:<path
    to .jar file>:.
JDBC Driver Management
• All drivers are managed by the DriverManager
  class
• Example - loading an Oracle JDBC driver:
  – In the Java code:
    Class.forName(“oracle.jdbc.driver.OracleDriver”)
• Driver class names:
  Oracle: oracle.jdbc.driver.OracleDriver
  MySQL: com.mysql.jdbc.Driver
  MS SQL Server:
  com.microsoft.jdbc.sqlserver.SQLServerDriver
Establishing a Connection
• Create a Connection object
• Use the DriverManager to grab a connection
  with the getConnection method
• Necessary to follow exact connection syntax
• Problem 1: the parameter syntax for
  getConnection varies between JDBC drivers
• Problem 2: one driver can have several
  different legal syntaxes
Establishing a Connection (cont.)
         Oracle Example
• Connection con =
  DriverManager.getConnection(string,
  “username", “password");
• what to supply for string ?
• “jdbc:oracle:thin:@augur.seas.gwu.edu:1521:orcl10g2”

     Driver   Type   Database URL    Port #   SID
Establishing a Connection (cont.)
        MySQL Example
• Connection con =
  DriverManager.getConnection(string);
• what to supply for string ?
• “jdbc:mysql://<URL>:3306/<DB>?user=<user>&password=<pw>”

     Driver    URL   Port    DB    Username       Password
                            Name
Executing Statements
• Obtain a statement object from the
  connection:
  – Statement stmt = con.createStatement ();
• Execute the SQL statements:
  – stmt.executeUpdate(“update table set
    field=‘value’”);
  – stmt.executeUpdate(“INSERT INTO mytable
    VALUES (1, ‘name’)”);
  – stmt.executeQuery(“SELECT * FROM mytable”);
Retrieving Data
• ResultSet rs =
  stmt.executeQuery(“SELECT id,name
  FROM employees where id = 1000”)
• Some methods used in ResultSet:
  – next()
  – getString()
  – getInt()
Using the Results
while (rs.next())
{
  float s = rs.getInt("id");
  String n = rs.getString("name");
  System.out.println(s + " " + n);
}
Connection Class Interface
• public boolean getReadOnly() and
  void setReadOnly(boolean b)
  Specifies whether transactions in this connection
  are read-only
• public boolean isClosed()
  Checks whether connection is still open.
• public boolean getAutoCommit() and
  void setAutoCommit(boolean b)
  If autocommit is set, then each SQL statement is
  considered its own transaction. Otherwise, a
  transaction is committed using commit(), or
  aborted using rollback().
Executing SQL Statements
• Three different ways of executing SQL
  statements:
  – Statement (both static and dynamic SQL
    statements)
  – PreparedStatement (semi-static SQL statements)
  – CallableStatment (stored procedures)
PreparedStatement class:Precompiled,
  parametrized SQL statements:
  – Structure is fixed
  – Values of parameters are determined at run-time
Executing SQL Statements
           (cont.)
String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”;
PreparedStatment pstmt=con.prepareStatement(sql);
pstmt.clearParameters();
pstmt.setInt(1,sid);
pstmt.setString(2,sname);
pstmt.setInt(3, rating);
pstmt.setFloat(4,age);
// we know that no rows are returned, thus we use
   executeUpdate()
int numRows = pstmt.executeUpdate();
ResultSets
• PreparedStatement.executeUpdate only returns
  the number of affected records
• PreparedStatement.executeQuery returns data,
  encapsulated in a ResultSet object (a cursor)

ResultSet rs=pstmt.executeQuery(sql);
// rs is now a cursor
While (rs.next()) {
  // process the data
}
ResultSets (cont.)
A ResultSet is a very powerful cursor:
• previous(): moves one row back
• absolute(int num): moves to the row with
  the specified number
• relative (int num): moves forward or
  backward
• first() and last()
Matching Java-SQL Data Types
SQL Type    Java class           ResultSet get method
BIT         Boolean              getBoolean()
CHAR        String               getString()
VARCHAR     String               getString()
DOUBLE      Double               getDouble()
FLOAT       Double               getDouble()
INTEGER     Integer              getInt()
REAL        Double               getFloat()
DATE        java.sql.Date        getDate()
TIME        java.sql.Time        getTime()
TIMESTAMP   java.sql.TimeStamp   getTimestamp()
JDBC: Exceptions and
           Warnings
• Most of java.sql can throw and
  SQLException if an error occurs (use
  try/catch blocks to find connection
  problems)
• SQLWarning is a subclass of
  EQLException; not as severe (they are not
  thrown and their existence has to be
  explicitly tested)
JDBC Cobweb example:
import java.sql.*;

public class JDBCexample {
     static String url ="jdbc:mysql://cobweb.seas.gwu.edu:3306/<DB>?user=<USERNAME>&password=<PASSWORD>";

     public static void main(String[] args) throws Exception {

         Connection con=null;

                 try {
                 Class.forName("com.mysql.jdbc.Driver");
           } catch(java.lang.ClassNotFoundException e) {
                 System.err.print("ClassNotFoundException: ");
                 System.err.println(e.getMessage());
           }

           try {
             con = DriverManager.getConnection(url);
             System.out.println("Got Connection.");

           } catch(SQLException ex) {
                 System.err.println("SQLException: " + ex.getMessage());
           }
     }
}
In class assignment

• Download the MySQL JDBC “driver”
  (Connector/J) from www.mysql.org and
  copy the .jar file to your cobweb account

• Write a java application to run a query on
  one of your tables and return the results to
  the command line.

Más contenido relacionado

La actualidad más candente

My sql with java
My sql with javaMy sql with java
My sql with java
oly07104
 

La actualidad más candente (20)

Jdbc
JdbcJdbc
Jdbc
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBCBI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
BI, Integration, and Apps on Couchbase using Simba ODBC and JDBC
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Database programming
Database programmingDatabase programming
Database programming
 
JDBC
JDBCJDBC
JDBC
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Jdbc
JdbcJdbc
Jdbc
 
My sql with java
My sql with javaMy sql with java
My sql with java
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 

Destacado

Bad packaging
Bad packagingBad packaging
Bad packaging
RBStinson
 
Victoria's alphabet
Victoria's alphabetVictoria's alphabet
Victoria's alphabet
17vicholden
 
Data driven recruiting
Data driven recruitingData driven recruiting
Data driven recruiting
Brendan Browne
 
Kế hoạch thực tế cộng đồng iii yến
Kế hoạch thực tế cộng đồng iii  yếnKế hoạch thực tế cộng đồng iii  yến
Kế hoạch thực tế cộng đồng iii yến
Nomel Lemon
 

Destacado (15)

Arezzo 16 aprile 2013 Apertura e Relazione Gianfranco Barbieri
Arezzo 16 aprile 2013  Apertura e Relazione Gianfranco BarbieriArezzo 16 aprile 2013  Apertura e Relazione Gianfranco Barbieri
Arezzo 16 aprile 2013 Apertura e Relazione Gianfranco Barbieri
 
Science presentation wed
Science presentation wedScience presentation wed
Science presentation wed
 
Bad packaging
Bad packagingBad packaging
Bad packaging
 
Science alpha beta gamma
Science alpha beta gammaScience alpha beta gamma
Science alpha beta gamma
 
Victoria's alphabet
Victoria's alphabetVictoria's alphabet
Victoria's alphabet
 
An English online comic about Nick Butch
An English online comic about Nick ButchAn English online comic about Nick Butch
An English online comic about Nick Butch
 
Juno Opening sequence powerpoint
Juno Opening sequence powerpointJuno Opening sequence powerpoint
Juno Opening sequence powerpoint
 
Data driven recruiting
Data driven recruitingData driven recruiting
Data driven recruiting
 
Restitution des données environnement Microsoft & data visualization : panel ...
Restitution des données environnement Microsoft & data visualization : panel ...Restitution des données environnement Microsoft & data visualization : panel ...
Restitution des données environnement Microsoft & data visualization : panel ...
 
Understanding Messaging and Chatbots
Understanding Messaging and ChatbotsUnderstanding Messaging and Chatbots
Understanding Messaging and Chatbots
 
La energia
La energiaLa energia
La energia
 
The Line It Is Drawn: Week 249
The Line It Is Drawn: Week 249The Line It Is Drawn: Week 249
The Line It Is Drawn: Week 249
 
Flores
FloresFlores
Flores
 
Doi dep
Doi depDoi dep
Doi dep
 
Kế hoạch thực tế cộng đồng iii yến
Kế hoạch thực tế cộng đồng iii  yếnKế hoạch thực tế cộng đồng iii  yến
Kế hoạch thực tế cộng đồng iii yến
 

Similar a Jdbc

30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
phanleson
 

Similar a Jdbc (20)

Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
JDBC
JDBCJDBC
JDBC
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Core Java Programming Language (JSE) : Chapter XIII -  JDBCCore Java Programming Language (JSE) : Chapter XIII -  JDBC
Core Java Programming Language (JSE) : Chapter XIII - JDBC
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Database connect
Database connectDatabase connect
Database connect
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 

Jdbc

  • 2. What is JDBC ? • JDBC stands for “Java DataBase Connectivity” • The standard interface for communication between a Java application and a SQL database • Allows a Java program to issue SQL statements and process the results.
  • 3. JDBC Classes and Interfaces Steps to using a database query: • Load a JDBC “driver” • Connect to the data source • Send/execute SQL statements • Process the results
  • 4. JDBC Driver • Acts as the gateway to a database • Not actually a “driver”, just a .jar file Java application Database Server JDBC Driver
  • 5. JDBC Driver Installation • Must download the driver, copy it to cobweb then add the .jar file to your $CLASSPATH • To set up your classpath, ssh into cobweb and execute the following command: – export CLASSPATH=$CLASSPATH:<path to .jar file>:.
  • 6. JDBC Driver Management • All drivers are managed by the DriverManager class • Example - loading an Oracle JDBC driver: – In the Java code: Class.forName(“oracle.jdbc.driver.OracleDriver”) • Driver class names: Oracle: oracle.jdbc.driver.OracleDriver MySQL: com.mysql.jdbc.Driver MS SQL Server: com.microsoft.jdbc.sqlserver.SQLServerDriver
  • 7. Establishing a Connection • Create a Connection object • Use the DriverManager to grab a connection with the getConnection method • Necessary to follow exact connection syntax • Problem 1: the parameter syntax for getConnection varies between JDBC drivers • Problem 2: one driver can have several different legal syntaxes
  • 8. Establishing a Connection (cont.) Oracle Example • Connection con = DriverManager.getConnection(string, “username", “password"); • what to supply for string ? • “jdbc:oracle:thin:@augur.seas.gwu.edu:1521:orcl10g2” Driver Type Database URL Port # SID
  • 9. Establishing a Connection (cont.) MySQL Example • Connection con = DriverManager.getConnection(string); • what to supply for string ? • “jdbc:mysql://<URL>:3306/<DB>?user=<user>&password=<pw>” Driver URL Port DB Username Password Name
  • 10. Executing Statements • Obtain a statement object from the connection: – Statement stmt = con.createStatement (); • Execute the SQL statements: – stmt.executeUpdate(“update table set field=‘value’”); – stmt.executeUpdate(“INSERT INTO mytable VALUES (1, ‘name’)”); – stmt.executeQuery(“SELECT * FROM mytable”);
  • 11. Retrieving Data • ResultSet rs = stmt.executeQuery(“SELECT id,name FROM employees where id = 1000”) • Some methods used in ResultSet: – next() – getString() – getInt()
  • 12. Using the Results while (rs.next()) { float s = rs.getInt("id"); String n = rs.getString("name"); System.out.println(s + " " + n); }
  • 13. Connection Class Interface • public boolean getReadOnly() and void setReadOnly(boolean b) Specifies whether transactions in this connection are read-only • public boolean isClosed() Checks whether connection is still open. • public boolean getAutoCommit() and void setAutoCommit(boolean b) If autocommit is set, then each SQL statement is considered its own transaction. Otherwise, a transaction is committed using commit(), or aborted using rollback().
  • 14. Executing SQL Statements • Three different ways of executing SQL statements: – Statement (both static and dynamic SQL statements) – PreparedStatement (semi-static SQL statements) – CallableStatment (stored procedures) PreparedStatement class:Precompiled, parametrized SQL statements: – Structure is fixed – Values of parameters are determined at run-time
  • 15. Executing SQL Statements (cont.) String sql=“INSERT INTO Sailors VALUES(?,?,?,?)”; PreparedStatment pstmt=con.prepareStatement(sql); pstmt.clearParameters(); pstmt.setInt(1,sid); pstmt.setString(2,sname); pstmt.setInt(3, rating); pstmt.setFloat(4,age); // we know that no rows are returned, thus we use executeUpdate() int numRows = pstmt.executeUpdate();
  • 16. ResultSets • PreparedStatement.executeUpdate only returns the number of affected records • PreparedStatement.executeQuery returns data, encapsulated in a ResultSet object (a cursor) ResultSet rs=pstmt.executeQuery(sql); // rs is now a cursor While (rs.next()) { // process the data }
  • 17. ResultSets (cont.) A ResultSet is a very powerful cursor: • previous(): moves one row back • absolute(int num): moves to the row with the specified number • relative (int num): moves forward or backward • first() and last()
  • 18. Matching Java-SQL Data Types SQL Type Java class ResultSet get method BIT Boolean getBoolean() CHAR String getString() VARCHAR String getString() DOUBLE Double getDouble() FLOAT Double getDouble() INTEGER Integer getInt() REAL Double getFloat() DATE java.sql.Date getDate() TIME java.sql.Time getTime() TIMESTAMP java.sql.TimeStamp getTimestamp()
  • 19. JDBC: Exceptions and Warnings • Most of java.sql can throw and SQLException if an error occurs (use try/catch blocks to find connection problems) • SQLWarning is a subclass of EQLException; not as severe (they are not thrown and their existence has to be explicitly tested)
  • 20. JDBC Cobweb example: import java.sql.*; public class JDBCexample { static String url ="jdbc:mysql://cobweb.seas.gwu.edu:3306/<DB>?user=<USERNAME>&password=<PASSWORD>"; public static void main(String[] args) throws Exception { Connection con=null; try { Class.forName("com.mysql.jdbc.Driver"); } catch(java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url); System.out.println("Got Connection."); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } } }
  • 21. In class assignment • Download the MySQL JDBC “driver” (Connector/J) from www.mysql.org and copy the .jar file to your cobweb account • Write a java application to run a query on one of your tables and return the results to the command line.

Notas del editor

  1. Will be using Oracle later in the semester.
  2. No exercise since students need to download a MySQL driver.
  3. Not going to go over transaction processing yet.
  4. Cursor is just a “pointer” to the current row