SlideShare a Scribd company logo
Java course - IAG0040




             JDBC & Logging




Anton Keks                            2011
JDBC
 ●
     Java DataBase Connectivity
     –   The API for DB access from Java
     –   Oriented towards relational databases
     –   java.sql package
     –   JDBC is DB vendor neutral
 ●   Versions
     –   Exists since Java 1.1
     –   Java 1.4 & 1.5 ships with JDBC 3
     –   Java 1.6 introduced JDBC 4
Java course - IAG0040                            Lecture 13
Anton Keks                                           Slide 2
JDBC drivers
 ●
     java.sql.Driver - the driver side of the JDBC
     layer is the part that interfaces with the
     actual database, and therefore is generally
     written by database vendors
 ●
     Most developers only need to know how to
     install and use drivers. The JDBC Driver API
     defines a set of interfaces which have to be
     implemented by a vendor


Java course - IAG0040                          Lecture 13
Anton Keks                                         Slide 3
JDBC driver types
 ●
     Type 1 use a bridge technology to connect a Java client to
     ODBC system. The JDBC-ODBC bridge from Sun is one example
     of a Type 1 driver
 ●   Type 2 use native code library to access a database, wrapping
     a thin layer of Java around the native library, e.g. Oracle OCI
     driver
 ●   Type 3 drivers define a generic network protocol that
     interfaces with a piece of custom middleware. The
     middleware component might use any other type of driver to
     provide the actual database access.
 ●   Type 4 drivers are implemented entirely in Java. They
     understand database-specific networking protocols and can
     access the database directly without any additional software.
Java course - IAG0040                                        Lecture 13
Anton Keks                                                       Slide 4
JDBC driver summary

     Type 1              ODBC
   ODBC bridge           diver


     Type 2             Native API
    Native API

      Type 3                         Middleware
                                                  DB
      Network                          server


      Type 4
     Pure Java


Java course - IAG0040                             Lecture 13
Anton Keks                                            Slide 5
JDBC API basics
                        ResultSet


           Statement            PreparedStatement     CallableStatement



                                      Connection
    Application

                                    DriverManager

                                                       Oracle, MySQL,
                                    Concrete Driver     PostgreSQL,
                                                        HSQLDB, etc


                                     Concrete DB


Java course - IAG0040                                               Lecture 13
Anton Keks                                                              Slide 6
JDBC basic usage
 ●
     Load the driver (was needed before JDBC 4)
     –   Class.forName(“driverClassName”);
     –   System property -Djdbc.drivers=driverClassName
 ●
     Use DriverManager to create connection
     –   DriverManager.getConnection(url, user, password);
 ●
     Create statement for execution
     –   connection.createStatement();
 ●
     Execute the query and get a ResultSet
     –   statement.executeQuery(sql);
 ●   Iterate over ResultSet: rs.next() and rs.getXXX()
 ●   Free resources with close() methods
Java course - IAG0040                                     Lecture 13
Anton Keks                                                    Slide 7
Connection
 ●
     java.sql.Connection
 ●   Represents an open connection to the DB
 ●   Obtained via a DriverManager
     –   DriverManager.getConnection(url, user, password)
 ●
     URL starts with jdbc:
     –   The exact format depends on the vendor
     –   jdbc:mysql://server:port/dbname
     –   jdbc:hsqldb:mem:dbname
     –   jdbc:oracle:thin:@server:port:sid
Java course - IAG0040                              Lecture 13
Anton Keks                                             Slide 8
Statement & PreparedStatement
 ●
     java.sql.Statement
      –   for execution of simple statements without
          parameters
      –   s = conn.createStatement();
          s.execute(“CREATE TABLE ..”);

 ●
     java.sql.PreparedStatement
      –   for execution of parametrized statements via
          'parameter binding'
      –   s = conn.prepareStatement(“SELECT .. WHERE ID = ?”)
          s.setInt(1, value); ResultSet rs = s.executeQuery();
      –   allows for reuse of pre-compiled statements
Java course - IAG0040                                    Lecture 13
Anton Keks                                                   Slide 9
ResultSet
 ●
     java.sql.ResultSet
     –   represents result of a SQL query, containing
         multiple rows, similar to an Iterator
     –   ResultSet rs = s.executeQuery(“SELECT ...”);
         while (rs.next()) {
            rs.getString(1); or rs.getString(“COLUMN”);
         }
         rs.close();
     –   cursor movement by default is
         ResultSet.TYPE_FORWARD_ONLY
          ●   Some drivers may support bidirectional
              movement
Java course - IAG0040                                     Lecture 13
Anton Keks                                                  Slide 10
CallableStatement
 ●
     java.sql.CallableStatement
     –   extends PreparedStatement
     –   intended for calling stored procedures in the DB
     –   allows reading of OUT parameters instead of
         getting a ResultSet
     –   s = conn.prepareCall(“{call SOME_PROC(?, ?, ?)}”);
         s.setString(1, “some value”);
         s.registerOutParameter(2, Types.VARCHAR);
         s.registerOutParameter(3, Types.NUMERIC);

         s.execute();
         String result1 = s.getString(2);
         int result2 = s.getInt(3);

Java course - IAG0040                                   Lecture 13
Anton Keks                                                Slide 11
Resourse Management
 ●
     All DB objects have the close() method
     –   higher-level DB objects automatically close the
         lower-level ones
     –   conn.close() will close all underlying statements
 ●   Don't forget proper closing
     –   same pattern applies as with java.io
     –   it is a good idea to put close() into a finally block!



Java course - IAG0040                                    Lecture 13
Anton Keks                                                 Slide 12
Metadata
 ●
     DatabaseMetaData, ResultSetMetaData,
     ParameterMetaData
     –   Metadata provides additional information about
         the respective DB objects
     –   Can be used for discovering of DB structure and
         other 'advanced' or non-standard code
     –   DatabaseMetaData metadata = conn.getMetaData();
         String name = metadata.getDatabaseProductName();
     –   ResultSet rs = s.executeQuery(“SELECT ...”);
         ResultSetMetaData metadata = rs.getMetaData();
         int columns = metadata.getColumnCount();


Java course - IAG0040                                     Lecture 13
Anton Keks                                                  Slide 13
Transactions
 ●
     Connection auto-commit is ON by default
     –   Use conn.setAutoCommit(false) to control
         transactions manually
 ●
     Transaction control
     –   connection.commit() persists the changes
     –   connection.rollback() cancels the changes
     –   connection.setSavepoint() bookmarks transactions
     –   exact behaviour depends on the concrete DB


Java course - IAG0040                                 Lecture 13
Anton Keks                                              Slide 14
DataSource
 ●
     java.sql.DataSource
     –   a bean-style alternative to DriverManager
     –   implemented by a DB vendor
 ●   Is usually initialized in a vendor-specific way in
     the application container
     –   provides getConnection() method
 ●   Spring Framework and Commons-DBCP have
     useful implementations, e.g. for connection
     pooling
Java course - IAG0040                                Lecture 13
Anton Keks                                             Slide 15
Data Access Patterns
 ●
     Define where to put the JDBC-related code in
     an application
 ●   In general:
     –   Isolate and encapsulate JDBC code
     –   Very few classes should know where the data
         comes from
     –   Pass data around as domain objects, not ResultSets
         or a mix of Strings or primitive types



Java course - IAG0040                               Lecture 13
Anton Keks                                            Slide 16
Active Domain Object Pattern
 ●
     aka ActiveRecord
 ●   Wraps a row in a table or view, encapsulates
     DB access, and adds domain logic
     –   JDBC only used internally, not visible from the
         outside
     –   Person person = Person.create();
         person.setName(“John Doe”);
         person.save();
     –   Person person = Person.load(“John Doe”);



Java course - IAG0040                                 Lecture 13
Anton Keks                                              Slide 17
Data Accessor Pattern
 ●
     aka Data Access Object (DAO)
 ●   Encapsulates physical data access in a single
     component, exposing logical operations
     –   Application code maintains knowledge about the
         underlying data model, but is decoupled from the
         data access possibilities
     –   Domain objects know nothing about the DB
     –   PersonAccessor dao = new JDBCPersonAccessor();
         Person person = dao.loadPerson(“John Doe”);
         person.setName(“John Smith”);
         dao.save(person);

Java course - IAG0040                               Lecture 13
Anton Keks                                            Slide 18
Testing
 ●
     Clear separation of DB access logic from
     business logic makes testing and maintenance
     a lot easier
 ●
     All JDBC interfaces can be easily mocked
     –   Connection conn = createMock(Connection.class);
 ●
     Sometimes it is wise to test the full-cycle
     –   Use in-memory database, e.g. HSQLDB
     –   Initialize the data there and substitute DB
         connection with the fake in-memory one
     –   DBUnit can help with that
Java course - IAG0040                                  Lecture 13
Anton Keks                                               Slide 19
Logging
 ●   When writing more complex applications, you need logging in
     your code
      –   you don't want to show low-level crash info to end-users
      –   debugging of bugs on production is usually not possible
 ●   There are many possibilities to implement logging:
      –   System.out / System.err or other java.io classes – usually
          primitive and not flexible solution
      –   java.util.logging, e.g. Logger class – logging API included in Java
          since 1.4, configurable and extensible
      –   Log4J – very popular de-facto standard framework, very
          powerful, has a very good API
      –   Jakarta commons-logging – the facade for different logging APIs
Java course - IAG0040                                                Lecture 13
Anton Keks                                                             Slide 20
java.util.logging
 ●   Logger LOG = Logger.getLogger(this.getClass().getName());
      –   Loggers have hierarchical structure ('.' separated), it is a good idea to use
          full class name as a logger name
      –   Logger often used as a static member (for convenience)
 ●   Loggers can be used for logging information with various levels
      –   SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST
      –   LOG.severe(“We have a problem!”);
      –   LOG.log(Level.SEVERE, “We have a problem”, exception);
 ●   java.util.logging is configurable
      –   by default it uses $JAVA_HOME/jre/lib/logging.properties
      –   specific file is specified with sys. property java.util.logging.config.file


Java course - IAG0040                                                           Lecture 13
Anton Keks                                                                        Slide 21
java.util.logging (cont)
 ●   Logger is used to produce LogRecords
      –   every LogRecord has a specified logging Level
      –   every Logger may have its own Level assigned
      –   or they inherit Level from their parent
 ●   LogRecords are passed to one or more Handlers
      –   e.g. ConsoleHandler, FileHandler, MemoryHandler, SocketHandler, etc
      –   every handler writes logs greater or equal to their assigned Level
 ●   Formatters are used for formatting of LogRecords
      –   SimpleFormatter or XMLFormatter
 ●   a LogRecord is written only if its Level is greater than of its Logger's and if
     there is a Handler configured to write at this Level
 ●   Filters may be used for more fine-grained control of what should be logged

Java course - IAG0040                                                        Lecture 13
Anton Keks                                                                     Slide 22
Log4J (org.apache.log4j)
 ●   Logger LOG = Logger.getLogger(this.getClass());
      –   Loggers have hierarchical structure ('.' separated), same as util.logging
 ●   Loggers can be used for logging information with various levels
      –   FATAL, ERROR, WARN, INFO, DEBUG are default levels
      –   LOG.error(“We have a problem!”, exception);
 ●   Log4J is fully configurable with external files
      –   there is no default configuration
      –   it automatically looks for log4j.xml or log4j.properties in classpath
      –   can be overriden with log4j.configuration system property
      –   every named logger can have its own configuration
      –   different appenders can be used for writing the actual data

Java course - IAG0040                                                      Lecture 13
Anton Keks                                                                   Slide 23

More Related Content

What's hot

Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
Sagar Verma
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
Core java
Core java Core java
Core java
Ravi varma
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
Allan Huang
 
Core java1
Core java1Core java1
Core java1
Ravi varma
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
Core Java
Core JavaCore Java
Core Java
Prakash Dimmita
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
APSMIND TECHNOLOGY PVT LTD.
 
Java 9
Java 9Java 9
Java 9
Netesh Kumar
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
What is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK TechnologiesWhat is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK Technologies
PSK Technolgies Pvt. Ltd. IT Company Nagpur
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Professional Guru
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
Anton Shchastnyi
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Edureka!
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
Ideal Eyes Business College
 

What's hot (20)

Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Core java
Core java Core java
Core java
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Core java1
Core java1Core java1
Core java1
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Core Java
Core JavaCore Java
Core Java
 
Java basic
Java basicJava basic
Java basic
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
 
Java 9
Java 9Java 9
Java 9
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
What is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK TechnologiesWhat is Java? Presentation On Introduction To Core Java By PSK Technologies
What is Java? Presentation On Introduction To Core Java By PSK Technologies
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 

Similar to Java Course 13: JDBC & Logging

Jdbc
JdbcJdbc
JDBC
JDBCJDBC
Jdbc
Jdbc   Jdbc
Jdbc
Ishucs
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
Chapter 5 JDBC.pdf for stufent of computer andtudent  It sChapter 5 JDBC.pdf for stufent of computer andtudent  It s
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
anuwaradisu19
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
guest04b824
 
Jdbc
JdbcJdbc
Jdbc
Ishucs
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
DevAdnani
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
snopteck
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
snopteck
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
Niit Care
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
Rakesh Kumar Ray
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
bhagyashri686896
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
VisionAcademyProfSac
 
Jdbc
JdbcJdbc
Java session16
Java session16Java session16
Java session16
Niit Care
 
Jdbc new
Jdbc newJdbc new
Jdbc new
sumit kushwah
 
Jdbc
JdbcJdbc
Jdbc
JdbcJdbc
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
Juarez Junior
 

Similar to Java Course 13: JDBC & Logging (20)

Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
Jdbc   Jdbc
Jdbc
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
Chapter 5 JDBC.pdf for stufent of computer andtudent  It sChapter 5 JDBC.pdf for stufent of computer andtudent  It s
Chapter 5 JDBC.pdf for stufent of computer andtudent It s
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
Jdbc session01
Jdbc session01Jdbc session01
Jdbc session01
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
 
Jdbc
JdbcJdbc
Jdbc
 
Java session16
Java session16Java session16
Java session16
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
TDC Connections 2023 - Revolutionize Java DB AppDev with Reactive Streams and...
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
Anton Keks
 

More from Anton Keks (10)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
313mohammedarshad
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
alexjohnson7307
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
Shiv Technolabs
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
Ivanti
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
DianaGray10
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
BrainSell Technologies
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
SynapseIndia
 
Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
Matthias Neugebauer
 

Recently uploaded (20)

The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
 
Opencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of MünsterOpencast Summit 2024 — Opencast @ University of Münster
Opencast Summit 2024 — Opencast @ University of Münster
 

Java Course 13: JDBC & Logging

  • 1. Java course - IAG0040 JDBC & Logging Anton Keks 2011
  • 2. JDBC ● Java DataBase Connectivity – The API for DB access from Java – Oriented towards relational databases – java.sql package – JDBC is DB vendor neutral ● Versions – Exists since Java 1.1 – Java 1.4 & 1.5 ships with JDBC 3 – Java 1.6 introduced JDBC 4 Java course - IAG0040 Lecture 13 Anton Keks Slide 2
  • 3. JDBC drivers ● java.sql.Driver - the driver side of the JDBC layer is the part that interfaces with the actual database, and therefore is generally written by database vendors ● Most developers only need to know how to install and use drivers. The JDBC Driver API defines a set of interfaces which have to be implemented by a vendor Java course - IAG0040 Lecture 13 Anton Keks Slide 3
  • 4. JDBC driver types ● Type 1 use a bridge technology to connect a Java client to ODBC system. The JDBC-ODBC bridge from Sun is one example of a Type 1 driver ● Type 2 use native code library to access a database, wrapping a thin layer of Java around the native library, e.g. Oracle OCI driver ● Type 3 drivers define a generic network protocol that interfaces with a piece of custom middleware. The middleware component might use any other type of driver to provide the actual database access. ● Type 4 drivers are implemented entirely in Java. They understand database-specific networking protocols and can access the database directly without any additional software. Java course - IAG0040 Lecture 13 Anton Keks Slide 4
  • 5. JDBC driver summary Type 1 ODBC ODBC bridge diver Type 2 Native API Native API Type 3 Middleware DB Network server Type 4 Pure Java Java course - IAG0040 Lecture 13 Anton Keks Slide 5
  • 6. JDBC API basics ResultSet Statement PreparedStatement CallableStatement Connection Application DriverManager Oracle, MySQL, Concrete Driver PostgreSQL, HSQLDB, etc Concrete DB Java course - IAG0040 Lecture 13 Anton Keks Slide 6
  • 7. JDBC basic usage ● Load the driver (was needed before JDBC 4) – Class.forName(“driverClassName”); – System property -Djdbc.drivers=driverClassName ● Use DriverManager to create connection – DriverManager.getConnection(url, user, password); ● Create statement for execution – connection.createStatement(); ● Execute the query and get a ResultSet – statement.executeQuery(sql); ● Iterate over ResultSet: rs.next() and rs.getXXX() ● Free resources with close() methods Java course - IAG0040 Lecture 13 Anton Keks Slide 7
  • 8. Connection ● java.sql.Connection ● Represents an open connection to the DB ● Obtained via a DriverManager – DriverManager.getConnection(url, user, password) ● URL starts with jdbc: – The exact format depends on the vendor – jdbc:mysql://server:port/dbname – jdbc:hsqldb:mem:dbname – jdbc:oracle:thin:@server:port:sid Java course - IAG0040 Lecture 13 Anton Keks Slide 8
  • 9. Statement & PreparedStatement ● java.sql.Statement – for execution of simple statements without parameters – s = conn.createStatement(); s.execute(“CREATE TABLE ..”); ● java.sql.PreparedStatement – for execution of parametrized statements via 'parameter binding' – s = conn.prepareStatement(“SELECT .. WHERE ID = ?”) s.setInt(1, value); ResultSet rs = s.executeQuery(); – allows for reuse of pre-compiled statements Java course - IAG0040 Lecture 13 Anton Keks Slide 9
  • 10. ResultSet ● java.sql.ResultSet – represents result of a SQL query, containing multiple rows, similar to an Iterator – ResultSet rs = s.executeQuery(“SELECT ...”); while (rs.next()) { rs.getString(1); or rs.getString(“COLUMN”); } rs.close(); – cursor movement by default is ResultSet.TYPE_FORWARD_ONLY ● Some drivers may support bidirectional movement Java course - IAG0040 Lecture 13 Anton Keks Slide 10
  • 11. CallableStatement ● java.sql.CallableStatement – extends PreparedStatement – intended for calling stored procedures in the DB – allows reading of OUT parameters instead of getting a ResultSet – s = conn.prepareCall(“{call SOME_PROC(?, ?, ?)}”); s.setString(1, “some value”); s.registerOutParameter(2, Types.VARCHAR); s.registerOutParameter(3, Types.NUMERIC); s.execute(); String result1 = s.getString(2); int result2 = s.getInt(3); Java course - IAG0040 Lecture 13 Anton Keks Slide 11
  • 12. Resourse Management ● All DB objects have the close() method – higher-level DB objects automatically close the lower-level ones – conn.close() will close all underlying statements ● Don't forget proper closing – same pattern applies as with java.io – it is a good idea to put close() into a finally block! Java course - IAG0040 Lecture 13 Anton Keks Slide 12
  • 13. Metadata ● DatabaseMetaData, ResultSetMetaData, ParameterMetaData – Metadata provides additional information about the respective DB objects – Can be used for discovering of DB structure and other 'advanced' or non-standard code – DatabaseMetaData metadata = conn.getMetaData(); String name = metadata.getDatabaseProductName(); – ResultSet rs = s.executeQuery(“SELECT ...”); ResultSetMetaData metadata = rs.getMetaData(); int columns = metadata.getColumnCount(); Java course - IAG0040 Lecture 13 Anton Keks Slide 13
  • 14. Transactions ● Connection auto-commit is ON by default – Use conn.setAutoCommit(false) to control transactions manually ● Transaction control – connection.commit() persists the changes – connection.rollback() cancels the changes – connection.setSavepoint() bookmarks transactions – exact behaviour depends on the concrete DB Java course - IAG0040 Lecture 13 Anton Keks Slide 14
  • 15. DataSource ● java.sql.DataSource – a bean-style alternative to DriverManager – implemented by a DB vendor ● Is usually initialized in a vendor-specific way in the application container – provides getConnection() method ● Spring Framework and Commons-DBCP have useful implementations, e.g. for connection pooling Java course - IAG0040 Lecture 13 Anton Keks Slide 15
  • 16. Data Access Patterns ● Define where to put the JDBC-related code in an application ● In general: – Isolate and encapsulate JDBC code – Very few classes should know where the data comes from – Pass data around as domain objects, not ResultSets or a mix of Strings or primitive types Java course - IAG0040 Lecture 13 Anton Keks Slide 16
  • 17. Active Domain Object Pattern ● aka ActiveRecord ● Wraps a row in a table or view, encapsulates DB access, and adds domain logic – JDBC only used internally, not visible from the outside – Person person = Person.create(); person.setName(“John Doe”); person.save(); – Person person = Person.load(“John Doe”); Java course - IAG0040 Lecture 13 Anton Keks Slide 17
  • 18. Data Accessor Pattern ● aka Data Access Object (DAO) ● Encapsulates physical data access in a single component, exposing logical operations – Application code maintains knowledge about the underlying data model, but is decoupled from the data access possibilities – Domain objects know nothing about the DB – PersonAccessor dao = new JDBCPersonAccessor(); Person person = dao.loadPerson(“John Doe”); person.setName(“John Smith”); dao.save(person); Java course - IAG0040 Lecture 13 Anton Keks Slide 18
  • 19. Testing ● Clear separation of DB access logic from business logic makes testing and maintenance a lot easier ● All JDBC interfaces can be easily mocked – Connection conn = createMock(Connection.class); ● Sometimes it is wise to test the full-cycle – Use in-memory database, e.g. HSQLDB – Initialize the data there and substitute DB connection with the fake in-memory one – DBUnit can help with that Java course - IAG0040 Lecture 13 Anton Keks Slide 19
  • 20. Logging ● When writing more complex applications, you need logging in your code – you don't want to show low-level crash info to end-users – debugging of bugs on production is usually not possible ● There are many possibilities to implement logging: – System.out / System.err or other java.io classes – usually primitive and not flexible solution – java.util.logging, e.g. Logger class – logging API included in Java since 1.4, configurable and extensible – Log4J – very popular de-facto standard framework, very powerful, has a very good API – Jakarta commons-logging – the facade for different logging APIs Java course - IAG0040 Lecture 13 Anton Keks Slide 20
  • 21. java.util.logging ● Logger LOG = Logger.getLogger(this.getClass().getName()); – Loggers have hierarchical structure ('.' separated), it is a good idea to use full class name as a logger name – Logger often used as a static member (for convenience) ● Loggers can be used for logging information with various levels – SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST – LOG.severe(“We have a problem!”); – LOG.log(Level.SEVERE, “We have a problem”, exception); ● java.util.logging is configurable – by default it uses $JAVA_HOME/jre/lib/logging.properties – specific file is specified with sys. property java.util.logging.config.file Java course - IAG0040 Lecture 13 Anton Keks Slide 21
  • 22. java.util.logging (cont) ● Logger is used to produce LogRecords – every LogRecord has a specified logging Level – every Logger may have its own Level assigned – or they inherit Level from their parent ● LogRecords are passed to one or more Handlers – e.g. ConsoleHandler, FileHandler, MemoryHandler, SocketHandler, etc – every handler writes logs greater or equal to their assigned Level ● Formatters are used for formatting of LogRecords – SimpleFormatter or XMLFormatter ● a LogRecord is written only if its Level is greater than of its Logger's and if there is a Handler configured to write at this Level ● Filters may be used for more fine-grained control of what should be logged Java course - IAG0040 Lecture 13 Anton Keks Slide 22
  • 23. Log4J (org.apache.log4j) ● Logger LOG = Logger.getLogger(this.getClass()); – Loggers have hierarchical structure ('.' separated), same as util.logging ● Loggers can be used for logging information with various levels – FATAL, ERROR, WARN, INFO, DEBUG are default levels – LOG.error(“We have a problem!”, exception); ● Log4J is fully configurable with external files – there is no default configuration – it automatically looks for log4j.xml or log4j.properties in classpath – can be overriden with log4j.configuration system property – every named logger can have its own configuration – different appenders can be used for writing the actual data Java course - IAG0040 Lecture 13 Anton Keks Slide 23