SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
Database access
               and JDBC

   Integrating database access into JSP
    applications
Goals
   Access SQL DBMS’s from JSP pages
     JDBC   technology
 Integrate SQL query results into the
  resulting HTML content
 Generate SQL queries according to FORM
  values
JDBC
 Standard library for accessing relational
  databases
 Compatible with most/all different
  databases
 JDBC : Java Database Connectivity
 Defined in package java.sql and javax.sql
 Documentation:
     http://java.sun.com/javase/technologies/databa
     se/index.jsp
Architecture
JDBC scope
   Standardizes
     Mechanism   for connecting to DBMSs
     Syntax for sending queries
     Structure representing the results
   Does not standardize
     SQL   syntax: dialects, variants, extensions, ...
Main elements
 Java application (in our case, JSP)
 JDBC Driver Manager
     For   loading the JDBC Driver
   JDBC Driver
     From   DBMS vendor
   DBMS
     In   our case, MySQL
Basic steps
 Load the JDBC driver
 Define the connection URL
 Establish the connection
 Create a statement object
 Execute a query or update
 Process the results
 Close the connection
1. Loading the driver
   A Driver is a DMBS-vendor provided class,
    that must be available to the Java
    application
     Must   reside in Tomcat’s CLASSPATH
 The application usually doesn’t know the
  driver class name until run-time (to ease
  the migration to other DMBSs)
 Needs to find and load the class at run-time
     Class.forName  method in the Java Class
      Loader (not needed in recent versions)
Types of drivers (1/3)
   A JDBC-ODBC bridge
     provides  JDBC API access via one or more
      ODBC drivers. ODBC native code must be
      loaded on each client machine that uses this
      type of driver.
   A native-API partly Java technology-
    enabled driver
     converts JDBC calls into calls on the client API
      for Oracle, Sybase, Informix, DB2, or other
      DBMS. Requires that some binary code be
      loaded on each client machine.
Types of drivers (2/3)
   A net-protocol fully Java technology-
    enabled driver
     translates JDBC API calls into a DBMS-
      independent net protocol which is then
      translated to a DBMS protocol by a server.
      Specific protocol depends on the vendor. The
      most flexible alternative
Types of drivers (3/3)
   A native-protocol fully Java technology-
    enabled driver
     converts  JDBC technology calls into the
      network protocol used by DBMSs directly.
      Direct call from the client machine to the DBMS
      server. Many of these protocols are
      proprietary: the database vendors will be the
      primary source for this style of driver.
MySQL JDBC driver
   MySQL® Connector/J
     http://www.mysql.com/products/connector/j/
   Provides mysql-connector-java-[version]-
    bin.jar
     Copy   into CLASSPATH
     E.g.: c:Program filesJavajre1.5.0_09libext
   The driver is in class
     com.mysql.jdbc.Driver
Loading the MySQL driver
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.jdbc.* or you will have problems!

public class LoadDriver {
  public static void main(String[] args) {
     try {
        // The newInstance() call is a work around for some
        // broken Java implementations

        Class.forName("com.mysql.jdbc.Driver").newInstance();
     } catch (Exception ex) { // mostly ClassNotFoundException
        // handle the error
     }
}
Loading the MySQL driver
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not Note: in recent versions of the Java problems!
                  import com.mysql.jdbc.* or you will have
                JVM, this step is no longer needed.
public class LoadDriver {
  public static void main(String[] args) {
     try {          The class is looked up in all the
                      libraries (.jar) found in the
        // The newInstance() call is a work around for some
                              CLASSPATH
        // broken Java implementations

        Class.forName("com.mysql.jdbc.Driver").newInstance();
     } catch (Exception ex) { // mostly ClassNotFoundException
        // handle the error
     }
}
2. Define the connection URL
   The Driver Manager needs some
    information to connect to the DBMS
     The  database type (to call the proper Driver,
      that we already loaded in the first step)
     The server address
     Authentication information (user/pass)
     Database / schema to connect to
   All these parameters are encoded into a
    string
     The   exact format depends on the Driver vendor
MySQL Connection URL format
   jdbc:mysql://[host:port],[host:port].../
    [database][?propertyName1]
    [=propertyValue1][&propertyName2]
    [=propertyValue2]...
     jdbc:mysql://
     host:port(localhost)
     /database
     ?user=username
     &password=ppppppp
3. Establish the connection
   Use DriverManager.getConnection
     Uses the appropriate driver according to the
      connection URL
     Returns a Connection object
 Connection connection =
  DriverManager.getConnection(URLString)
 Contacts DBMS, validates user and selects
  the database
 On the Connection object subsequent
  commands will execute queries
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

     try {
        Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test?
user=monty&password=greatsqldb");
        // Do something with the Connection
       ....
     } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
     }
4. Create a Statement object
 Statement statement =
  connection.createStatement() ;
 Creates a Statement object for sending
  SQL statements to the database.
 SQL statements without parameters are
  normally executed using Statement objects.
     Ifthe same SQL statement is executed many
      times, it may be more efficient to use a
      PreparedStatement object.
5. Execute a query
   Use the executeQuery method of the
    Statement class
     ResultSet  executeQuery(String sql)
     sql contains a SELECT statement
   Returns a ResultSet object, that will be
    used to retrieve the query results
Other execute methods
   int executeUpdate(String sql)
     For INSERT, UPDATE, or DELETE statements
     For other SQL statements that don’t return a
      resultset (e.g., CREATE TABLE)
     returns either the row count for INSERT,
      UPDATE or DELETE statements, or 0 for SQL
      statements that return nothing
   boolean execute(String sql)
     For   general SQL statements
Example


String query = "SELECT col1, col2, col3
FROM sometable" ;
ResultSet resultSet =
statement.executeQuery(query) ;
6. Process the result
   The ResultSet object implements a “cursor”
    over the query results
     Data    are available a row at a time
          Method ResultSet.next() goes to the next row
     The  column values (for the selected row) are
      available trhough getXXX methods
          getInt, getString, ...
     Data types are converted from SQL types to
      Java types
ResultSet.getXXX methods
   XXX is the desired datatype
     Must  be compatible with the column type
     String is almost always acceptable
   Two versions
     getXXX(int     columnIndex)
          number of column to retrieve (starting from 1!!!!)
     getXXX(String       columnName)
          name of column to retrieve
ResultSet navigation methods
   boolean next()
     Moves  the cursor down one row from its
      current position.
     NOTE: A ResultSet cursor is initially positioned
      before the first row; the first call to the method
      next makes the first row the current row; the
      second call makes the second row the current
      row, and so on.
Other navigation methods (1/2)
   Query cursor position
     boolean isFirst()
     boolean isLast()
     boolean isBeforeFirst()
     boolean isAfterLast()
Other navigation methods (2/2)
   Move cursor
     void beforeFirst()
     void afterLast()
     boolean first()
     boolean last()
     boolean absolute(int row)
     boolean relative(int rows) // positive or negative
      offset
     boolean previous()
Example
while( resultSet.next() )
{
  out.println( "<p>" +
    resultSet.getString(1) + " - " +
    resultSet.getString(2) + " - " +
    resultSet.getString(3) + "</p>" ) ;
}
Datatype conversions (MySQL)
                            Can always be converted to
These MySQL Data Types      these Java types
                            java.lang.String,
                            java.io.InputStream,
CHAR, VARCHAR, BLOB, TEXT, java.io.Reader, java.sql.Blob,
ENUM, and SET               java.sql.Clob
FLOAT, REAL, DOUBLE         java.lang.String, java.lang.Short,
PRECISION, NUMERIC,         java.lang.Integer, java.lang.Long,
DECIMAL, TINYINT, SMALLINT, java.lang.Double,
MEDIUMINT, INTEGER, BIGINT java.math.BigDecimal
DATE, TIME, DATETIME,       java.lang.String, java.sql.Date,
TIMESTAMP                   java.sql.Timestamp
7. Close the connection
   Additional queries may be done on the
    same connection.
     Each returns a different ResultSet object,
      unless you re-use it
   When no additional queries are needed:
     connection.close()   ;
References
   JDBC Basics: Tutorial
      http://java.sun.com/docs/books/tutorial/jdbc/ba
       sics/index.html
   JDBC reference guide
      http://java.sun.com/javase/6/docs/technotes/gu
       ides/jdbc/getstart/GettingStartedTOC.fm.html
   JDBC JavaDoc
      http://java.sun.com/javase/6/docs/api/java/sql/
       package-summary.html
      http://java.sun.com/javase/6/docs/api/javax/sql
       /package-summary.html

Weitere ähnliche Inhalte

Was ist angesagt? (20)

JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Jdbc
JdbcJdbc
Jdbc
 
Database connect
Database connectDatabase connect
Database connect
 
Jdbc
JdbcJdbc
Jdbc
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Jdbc
JdbcJdbc
Jdbc
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
JAXB
JAXBJAXB
JAXB
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
JDBC
JDBCJDBC
JDBC
 

Andere mochten auch

Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldabaux singapore
 
Open Source Creativity
Open Source CreativityOpen Source Creativity
Open Source CreativitySara Cannon
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...Brian Solis
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)maditabalnco
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsBarry Feldman
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 

Andere mochten auch (7)

Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 
Open Source Creativity
Open Source CreativityOpen Source Creativity
Open Source Creativity
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Ähnlich wie JDBC programming (20)

Database access and JDBC
Database access and JDBCDatabase access and JDBC
Database access and JDBC
 
JDBC
JDBCJDBC
JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
22jdbc
22jdbc22jdbc
22jdbc
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
JDBC
JDBCJDBC
JDBC
 
Prashanthi
PrashanthiPrashanthi
Prashanthi
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 

Kürzlich hochgeladen

Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 

Kürzlich hochgeladen (20)

prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 

JDBC programming

  • 1. Database access and JDBC  Integrating database access into JSP applications
  • 2. Goals  Access SQL DBMS’s from JSP pages  JDBC technology  Integrate SQL query results into the resulting HTML content  Generate SQL queries according to FORM values
  • 3. JDBC  Standard library for accessing relational databases  Compatible with most/all different databases  JDBC : Java Database Connectivity  Defined in package java.sql and javax.sql  Documentation:  http://java.sun.com/javase/technologies/databa se/index.jsp
  • 5. JDBC scope  Standardizes  Mechanism for connecting to DBMSs  Syntax for sending queries  Structure representing the results  Does not standardize  SQL syntax: dialects, variants, extensions, ...
  • 6. Main elements  Java application (in our case, JSP)  JDBC Driver Manager  For loading the JDBC Driver  JDBC Driver  From DBMS vendor  DBMS  In our case, MySQL
  • 7. Basic steps  Load the JDBC driver  Define the connection URL  Establish the connection  Create a statement object  Execute a query or update  Process the results  Close the connection
  • 8. 1. Loading the driver  A Driver is a DMBS-vendor provided class, that must be available to the Java application  Must reside in Tomcat’s CLASSPATH  The application usually doesn’t know the driver class name until run-time (to ease the migration to other DMBSs)  Needs to find and load the class at run-time  Class.forName method in the Java Class Loader (not needed in recent versions)
  • 9. Types of drivers (1/3)  A JDBC-ODBC bridge  provides JDBC API access via one or more ODBC drivers. ODBC native code must be loaded on each client machine that uses this type of driver.  A native-API partly Java technology- enabled driver  converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Requires that some binary code be loaded on each client machine.
  • 10. Types of drivers (2/3)  A net-protocol fully Java technology- enabled driver  translates JDBC API calls into a DBMS- independent net protocol which is then translated to a DBMS protocol by a server. Specific protocol depends on the vendor. The most flexible alternative
  • 11. Types of drivers (3/3)  A native-protocol fully Java technology- enabled driver  converts JDBC technology calls into the network protocol used by DBMSs directly. Direct call from the client machine to the DBMS server. Many of these protocols are proprietary: the database vendors will be the primary source for this style of driver.
  • 12. MySQL JDBC driver  MySQL® Connector/J  http://www.mysql.com/products/connector/j/  Provides mysql-connector-java-[version]- bin.jar  Copy into CLASSPATH  E.g.: c:Program filesJavajre1.5.0_09libext  The driver is in class  com.mysql.jdbc.Driver
  • 13. Loading the MySQL driver import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; // Notice, do not import com.mysql.jdbc.* or you will have problems! public class LoadDriver { public static void main(String[] args) { try { // The newInstance() call is a work around for some // broken Java implementations Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { // mostly ClassNotFoundException // handle the error } }
  • 14. Loading the MySQL driver import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; // Notice, do not Note: in recent versions of the Java problems! import com.mysql.jdbc.* or you will have JVM, this step is no longer needed. public class LoadDriver { public static void main(String[] args) { try { The class is looked up in all the libraries (.jar) found in the // The newInstance() call is a work around for some CLASSPATH // broken Java implementations Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception ex) { // mostly ClassNotFoundException // handle the error } }
  • 15. 2. Define the connection URL  The Driver Manager needs some information to connect to the DBMS  The database type (to call the proper Driver, that we already loaded in the first step)  The server address  Authentication information (user/pass)  Database / schema to connect to  All these parameters are encoded into a string  The exact format depends on the Driver vendor
  • 16. MySQL Connection URL format  jdbc:mysql://[host:port],[host:port].../ [database][?propertyName1] [=propertyValue1][&propertyName2] [=propertyValue2]...  jdbc:mysql://  host:port(localhost)  /database  ?user=username  &password=ppppppp
  • 17. 3. Establish the connection  Use DriverManager.getConnection  Uses the appropriate driver according to the connection URL  Returns a Connection object  Connection connection = DriverManager.getConnection(URLString)  Contacts DBMS, validates user and selects the database  On the Connection object subsequent commands will execute queries
  • 18. Example import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test? user=monty&password=greatsqldb"); // Do something with the Connection .... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }
  • 19. 4. Create a Statement object  Statement statement = connection.createStatement() ;  Creates a Statement object for sending SQL statements to the database.  SQL statements without parameters are normally executed using Statement objects.  Ifthe same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.
  • 20. 5. Execute a query  Use the executeQuery method of the Statement class  ResultSet executeQuery(String sql)  sql contains a SELECT statement  Returns a ResultSet object, that will be used to retrieve the query results
  • 21. Other execute methods  int executeUpdate(String sql)  For INSERT, UPDATE, or DELETE statements  For other SQL statements that don’t return a resultset (e.g., CREATE TABLE)  returns either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing  boolean execute(String sql)  For general SQL statements
  • 22. Example String query = "SELECT col1, col2, col3 FROM sometable" ; ResultSet resultSet = statement.executeQuery(query) ;
  • 23. 6. Process the result  The ResultSet object implements a “cursor” over the query results  Data are available a row at a time  Method ResultSet.next() goes to the next row  The column values (for the selected row) are available trhough getXXX methods  getInt, getString, ...  Data types are converted from SQL types to Java types
  • 24. ResultSet.getXXX methods  XXX is the desired datatype  Must be compatible with the column type  String is almost always acceptable  Two versions  getXXX(int columnIndex)  number of column to retrieve (starting from 1!!!!)  getXXX(String columnName)  name of column to retrieve
  • 25. ResultSet navigation methods  boolean next()  Moves the cursor down one row from its current position.  NOTE: A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
  • 26. Other navigation methods (1/2)  Query cursor position  boolean isFirst()  boolean isLast()  boolean isBeforeFirst()  boolean isAfterLast()
  • 27. Other navigation methods (2/2)  Move cursor  void beforeFirst()  void afterLast()  boolean first()  boolean last()  boolean absolute(int row)  boolean relative(int rows) // positive or negative offset  boolean previous()
  • 28. Example while( resultSet.next() ) { out.println( "<p>" + resultSet.getString(1) + " - " + resultSet.getString(2) + " - " + resultSet.getString(3) + "</p>" ) ; }
  • 29. Datatype conversions (MySQL) Can always be converted to These MySQL Data Types these Java types java.lang.String, java.io.InputStream, CHAR, VARCHAR, BLOB, TEXT, java.io.Reader, java.sql.Blob, ENUM, and SET java.sql.Clob FLOAT, REAL, DOUBLE java.lang.String, java.lang.Short, PRECISION, NUMERIC, java.lang.Integer, java.lang.Long, DECIMAL, TINYINT, SMALLINT, java.lang.Double, MEDIUMINT, INTEGER, BIGINT java.math.BigDecimal DATE, TIME, DATETIME, java.lang.String, java.sql.Date, TIMESTAMP java.sql.Timestamp
  • 30. 7. Close the connection  Additional queries may be done on the same connection.  Each returns a different ResultSet object, unless you re-use it  When no additional queries are needed:  connection.close() ;
  • 31. References  JDBC Basics: Tutorial  http://java.sun.com/docs/books/tutorial/jdbc/ba sics/index.html  JDBC reference guide  http://java.sun.com/javase/6/docs/technotes/gu ides/jdbc/getstart/GettingStartedTOC.fm.html  JDBC JavaDoc  http://java.sun.com/javase/6/docs/api/java/sql/ package-summary.html  http://java.sun.com/javase/6/docs/api/javax/sql /package-summary.html