Accessing a database from Java. Using JDBC

Similar documents
Tiers (or layers) Separation of concerns

Getting started with Winstone. Minimal servlet container

SQream Connector JDBC SQream Technologies Version 2.9.3

Accessing databases in Java using JDBC

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

Java Database Connectivity (JDBC) 25.1 What is JDBC?

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

DATABASE DESIGN I - 1DL300

JDBC [Java DataBase Connectivity]

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

SQL in a Server Environment

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

Introduction to Databases

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

Unit 3 - Java Data Base Connectivity

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

INTRODUCTION TO JDBC - Revised Spring

INTRODUCTION TO JDBC - Revised spring

Databases and MySQL. COMP 342: Programming Methods. 16 September Databases and MySQL

Databases 2012 Embedded SQL

Lab # 9. Java to Database Connection

DB I. 1 Dr. Ahmed ElShafee, Java course

Prepared Statement. Always be prepared

Java Database Connectivity

Pieter van den Hombergh. March 25, 2018

Working with Databases and Java

JAVA AND DATABASES. Summer 2018

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Backend. (Very) Simple server examples

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

JDBC Java Database Connectivity is a Java feature that lets you connect

Relational Databases. CS 240 Advanced Programming Concepts

13 Creation and Manipulation of Tables and Databases

Choosing output format. Dynamically choosing format

Programming in Java

Running SQL in Java and PHP

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

UNIT-3 Java Database Client/Server

C:/Users/zzaier/Documents/NetBeansProjects/WebApplication4/src/java/mainpackage/MainClass.java

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

Running SQL in Java and PHP

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Lab 6-1: MySQL Server

An IBM Rational Software TechNote

Tutorial: Using Java/JSP to Write a Web API

Visit for more.

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Distributed Systems Project 5 Assigned: Friday, April 6, 2012 Due: Friday, April 20, 11:59:59 PM

IBM DB DB2 application development Hands-On Lab. Information Management Cloud Computing Center of Competence. IBM Canada Lab

Database Application Programs PL/SQL, Java and the Web

Allenhouse Institute of Technology (UPTU Code : 505) OOT Notes By Hammad Lari for B.Tech CSE V th Sem

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

Logging and Recovery. 444 Section, April 23, 2009

Database Application Development Part 2 - Chapter

Builder pattern. A creational pattern

Workbook 5. Introduction. Using a database in Java. Important

Rev Up Your Car PC With Java Technology

Top 50 JDBC Interview Questions and Answers

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

SQL DML and DB Applications, JDBC

Advanced Programming Techniques. Database Systems. Christopher Moretti

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

Database Application Development

SqlC tutorial. 12 th may Revision 1.0. Visit us at

Student Number: Please fill out the identification section above as well as the one on the back page, and read the instructions below. Good Luck!

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Socket Programming(TCP & UDP) Sanjay Chakraborty

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

Secure Web App. 제목 : Secure Web Application v1.0 ( 채수민책임 ) Copyright 2008 Samsung SDS Co., Ltd. All rights reserved - 1 -

JDBC 3.0. Java Database Connectivity. 1 Java

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Database Application Development

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

IT 313 Advanced Application Development

Three-Tier Architecture

A Reliable tool for Hospital Administration System

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Persistency Patterns. Repository and DAO

Brekeke PBX Version 3 IVR Developer s Guide Brekeke Software, Inc.

Unit 2 JDBC Programming

VanillaCore Walkthrough Part 1. Introduction to Database Systems DataLab CS, NTHU

WEB SERVICES EXAMPLE 2

Database Assignment 2

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

Instructor: Jinze Liu. Fall 2008

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

Environment Settings on SIT

Real SQL Programming 1

Transcription:

Accessing a database from Java Using JDBC

We ve got a fuzzbox and we re gonna use it Now we know a little about databases and SQL. So how do we access a database from a Java application? There is an API for that, JDBC: http://www.oracle.com/technetwork/java/javase/jdbc/index.html

What do we need in order to use SQLite3? If we want to use our SQLite3 database from a Java application, we need a few things. First, we need a driver as a JAR file, and we need to make sure that it is on our CLASSPATH. https://bitbucket.org/xerial/sqlite-jdbc/downloads

Putting the driver on the classpath Let s say we have the following directory structure:. -- db -- app `-- DatabaseTest.java `-- main `-- Main.java -- driver `-- sqlite-jdbc-3.8.11.2.jar <----- The driver -- my_municipalities -- my_municipalities2 `-- textfiles -- HTTP-kommuner.txt --... and more files 5 directories, 18 files

Putting the driver on the classpath In order to use the driver in our Java application, we need to include it in the classpath: java -cp.:driver/sqlite-jdbc-3.8.11.2.jar db.main.main Note: sqlite-jdbc-3.8.11.2.jar is the exact filename of the driver you downloaded

Loading the driver inside Java static{ try{ Class.forName("org.sqlite.JDBC"); // Loads the class into the JVM catch(classnotfoundexception cnfe){ System.err.println("Could not load driver: " + cnfe.getmessage());

Classes in the JDBC API private static Connection con; private final static String DB_CONN_STR="jdbc:sqlite:my_municipalities"; /* When the connection is created, the appropriate driver is chosen */ try{ con = DriverManager.getConnection(DB_CONN_STR); catch(exception e){ System.err.println("Error getting connection to " + DB_CONN_STR);

Interfaces in the JDBC API /* import java.sql.*; First in this class we import java.sql.* */ Statement stm = null; ResultSet rs = null; try{ String query = "SELECT Name, HTTPS FROM municipalities LIMIT 5"; stm = con. createstatement(); rs = stm. executequery(query); while(rs. next()){ System.out.println(rs. getstring("name") + " " + (rs. getboolean("https")?"https support":"http only")); catch(sqlexception sqle){ System.err.println(sqle.getMessage()); finally{ try{ rs. close(); stm. close(); catch(exception e){

Putting it all together We ve provided a small test class for the basics of JDBC: Loading the driver class Creating a Connection Creating a Statement using the Connection Executing a query with the Statement and getting a... ResultSet back Looping through the rows of the ResultSet Getting the values from each row

package db.app; import java.sql.*; public class DatabaseTest{ private final static String DB_CONN_STR="jdbc:sqlite:my_municipalities"; static{ try{ Class.forName("org.sqlite.JDBC"); catch(classnotfoundexception cnfe){ System.err.println("Could not load driver: "+cnfe.getmessage()); Loading the driver class private static Connection con; public DatabaseTest(){ getconnection(); private void getconnection(){ try{ con = DriverManager.getConnection(DB_CONN_STR); catch(exception e){ System.err.println("Error getting connection to " + DB_CONN_STR); Getting a connection

public boolean hasconnection(){ return con!= null; public void testquery(){ if(hasconnection()){ Statement stm = null; ResultSet rs = null; try{ String query="select Name, HTTPS FROM municipalities LIMIT 5"; Creating a Statement Executing a query stm = con.createstatement(); rs = stm.executequery(query); while(rs.next()){ System.out.println(rs.getString("Name") + " " + Looping through the rows of the resultset and getting values from each row (rs.getboolean("https")?"https support":"http only")); catch(sqlexception sqle){ System.err.println(sqle.getMessage()); finally{ try{ rs.close(); stm.close(); catch(exception e){

The Main class package db.main; import db.app.databasetest; public class Main{ public static void main(string[] args){ System.out.println("Running db.main..."); DatabaseTest dt = new DatabaseTest(); if(dt.hasconnection()){ System.out.println("We have a connection"); else{ System.out.println("There was a problem getting a connection."); dt.testquery();

Running the code $ javac db/main/main.java && java -cp.:driver/sqlite-jdbc-3.8.11.2.jar db.main.main Running db.main... We have a connection Ale kommun HTTP only Alingsås kommun HTTPS support Alvesta kommun HTTP only Aneby kommun HTTP only Arboga kommun HTTP only

How can this work? How did Java know how to use the correct class? The key lies in the Connection and the use of interfaces. Class.forName("org.sqlite.JDBC"); // Will register with the DriverManager... con = DriverManager.getConnection(DB_CONN_STR); // Returns a java.sql.connection // What is that? public interface Connection http://docs.oracle.com/javase/7/docs/api/index.html?java/sql/connection.html

What interfaces exist in java.sql? [...] Connection [...] PreparedStatement (We ll look into that one later) [...] ResultSet [...] Statement [...]

The driver implements all required interfaces When we get a Connection object from the DriverManager, it actually asks the driver class which returns an instance of its implementation of the Connection interface.

Read https://docs.oracle.com/javase/tutorial/jdbc/index.html JDBC Introduction, and, Lesson: JDBC Basics: Getting Started Processing SQL Statements with JDBC Retrieving and Modifying Values from Result Sets