SQL (Structured Query Language) [3/21]
- SQL was a required skill for this class, and we aren't going to go over it
- If you're not familiar with SQL you might want to check out one of these tutorials after class
- And if you're not familiar with anything we go over in class please don't hesitate to ask
- SQL (Structured Query Language)
- Used to communicate with a database
- According to ANSI (American National Standards Institute), it is the standard language for relational database management systems
- Most supported version SQL-92
- SQL statements are used to perform tasks
- update data on a database, or retrieve data from a database
- Oracle, DB2, Sybase, Microsoft SQL Server, Access, PostgresSQL, MySQL, etc. all use SQL
- Basic Commands: "Select", "Insert", "Update", "Delete", "Create", and "Drop"
Basic commands [4/21]
SELECT what will this return when executed on our table?
SELECT instructor, course FROM schedule;
Optional WHERE clause allows comparison on =, <, >, <=, etc.
SELECT instructor, course FROM schedule WHERE instructor='Jungman';
Optional AND
SELECT instructor, course FROM schedule WHERE instructor='Jungman' AND day='Thursday';
CREATE
CREATE table employee
(first varchar(15),
last varchar(20),
age integer,
address varchar(30),
city varchar(20),
state varchar(20));
INSERT
INSERT into employee
(first, last, age, address, city, state)
values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia');
UPDATE
UPDATE employee set
age = 46 where last = Luke;
ODBC [5/21]
- Beyond SQL, different databases are surprisingly unique in their communication API
- Open Database Connectivity (ODBC) is an open standard application programming interface (API) for accessing a database.
- Allows you to access a number of different DB's from a programming language using SQL
- In addition to the ODBC software, a separate module or driver is needed for each database to be accessed.
- Provides DB independence for your code
JDBC [6/21]
- JDBC (which according to SUN's lawyers doesn't stand for Java DataBase Connectivity)
- Java's attempt to make Java database access platform independent
- Set of interfaces, which requires an implementing set of Driver classes usually provided by
a DB vendor to communicate to that particular database
- Must support SQL-92
- Sun provides a JDBC-ODBC bridge which allows us to reach ODBC-accessible databases
- ODBC is not sufficient for mission critical (secure, efficient) code
- It's fine to practice with
- Multiple versions of JDBC
- JDBC 1.0, 2.0, 3.0
- You need to know what your driver supports
Registering our DB on Win32 [7/21]
It doesn't really make a difference which database you use for the assignment I give,
so to simplify my grading either use MS-Access which is shipped with the professional version of MS-Office or Axion: http://axion.tigris.org/
Axion is an open source database written in Java, so it's platform independent, and it has a nice 'quick start' guide to setting up and calling the driver.
Here's a step-by-step tutorial on running a simple Java-to-MSAccess JDBC program.
If you don't have MS-Access (it comes with MS-Office) you can use the lab on the sixth floor
of CTI. You are of course welcome to use a non-MS environment as well.
- We'll create an MS-Access DB called myDB.mdb
- Search on your Windows machine for your "ODBC Data Source"; it is probably in your "Control Panel" which you may be able to access from Start->Settings... otherwise do a search
- Open your ODBC and click 'Add'
- Choose "Microsoft Access Driver" and click 'Finish'
- Fill in your "Data Source Name" field (I chose "TheDataSourceName" and then click "Select"
- Now find your Database in the directory and press O.K.
- You're ready to roll, the tutorial listed above has screen dumps of all this
Loading Your Driver [8/21]
- JDBC’s DriverManager
- Knows about different database formats
- For example, text (CSV), Oracle, dBase, etc
- Each database format has its own driver
- Driver information represented in a class
- Loading class registers driver with manager
- JDBC-ODBC "bridge" is provided
sun.jdbc.odbc.JdbcOdbcDriver
- Axion provides a different driver
org.axiondb.jdbc.AxionDriver
- More exhaustive list: http://industry.java.sun.com/products/jdbc/drivers
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("org.axiondb.jdbc.AxionDriver");
}
catch(ClassNotFoundException e)
{
/* exception handling */
}
Connect to the Database with DriverManager [9/21]
- Load appropriate database driver class
- Ask DriverManager for connection
- Database URL
- Rules are very fluid
- General format:
jdbc:subprotocol:identifier
getConnection(String url, String userName, String passWrd) or getConnection(String url)
- Check each loaded driver one by one to see if they understand the URL
- Different databases can support different amounts of simultaneous connections
- You must explicitly
.close() when done with the connection
- You can not rely on garbage collection
- Do this in the finally block. Why?
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection(
"jdbc:odbc:CustomerDB","","");
Class.forName("org.axiondb.jdbc.AxionDriver");
Connection con2 = DriverManager.getConnection("jdbc:axiondb:GradeDB:dbFile");
} ... // catch exceptions
//or
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String username = "epp";
String password = "dean1";
String URL = "jdbc:oracle:thin:@" + host + ":" + port + ":" dbName;
Connection c = DriverManager.getConnection(URL, username, pasword);
...}
java.sql.Statement [10/21]
- Talk to database using an object that implements the
Statement interface
- Represents a basic SQL statement
Statement stmt = con.createStatement();
- "Update" statements
- Create a table, drop a table, change records
- "Query" statements
- Find out what is in a table matching criteria
- Need to know SQL to execute statements in JDBC (at least in 1.0, more on that later)
Statment has two subinterfaces
PreparedStatement
CallableStatement
- More on those later
Creating a table [11/21]
(Say we wanted to create a new table, since we're doing a write to the database we use the .executeUpdate(String sql) method from the Statement interface)
- Form the SQL update string:
- Preamble: "CREATE TABLE" +
- Name the table: "TableName" +
- List the fields: "(Name1 Type1, ...)"
- An error occurs if the table already exists
- Need to "drop" the table before creating again
stmt.executeUpdate("CREATE TABLE Customers "
+ "(Cust_ID INTEGER, First_Name VARCHAR(20),"
+ " Last_Name VARCHAR(30), Street VARCHAR(30),"
+ " City VARCHAR(20), State VARCHAR(15),"
+ " Zip VARCHAR(10), Phone VARCHAR(15)," +
+ " Email VARCHAR(20), Credit_Card VARCHAR(16),"
+ " Exp_Month INTEGER, Exp_Year INTEGER)");
Storing data in a table [12/21]
- Inserting individual records into a table
- Creating the SQL insert string:
- Preamble: "INSERT INTO TableName" +
- Values for fields: "VALUES (Value1, ...)"
stmt.executeUpdate("INSERT INTO Customers " +
"VALUES (1,'J','C',‘Street','City','State'," +
"'60604', 'Email', 'CC', 12, 2001)");
Retrieving data from a table [13/21]
- Getting records from a table:
ResultSet rs = stmt.executeQuery(
"SELECT * FROM Customers");
- Gets all fields of all records in table
- ResultSet object is sequence of rows
- never null even if no rows were returned
- Use
next() to move through sequence
- getXxx(int), getXxx(String) to get fields
ResultSet rs =
stmt.executeQuery("SELECT * FROM Customers");
// rs.next() returns false if no more records
while (rs.next())
System.out.println(rs.getString("Last_Name") +
", " +
rs.getString("First_Name"));
- "SELECT *" gets all fields
- "SELECT FieldName1, FieldName2"
- Retrieves only those fields from records
- i.e. ResultSet rows will have only those fields
- Referring to fields in ResultSet
- getXxx(i) - i refers to ith selected field
- e.g.
getString("FieldName1") is equivalent to getString(1)
|
|
T I N Y I N T
|
S M A L L I N T
|
I N T E G E R
|
B I G I N T
|
R E A L
|
F L O A T
|
D O U B L E
|
D E C I M A L
|
N U M E R I C
|
B I T
|
C H A R
|
V A R C H A R
|
L O N G V A R C H A R
|
B I N A R Y
|
V A R B I N A R Y
|
L O N G V A R B I N A R Y
|
D A T E
|
T I M E
|
T I M E S T A M P
|
getByte
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getShort
|
x
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getInt
|
x
|
x
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getLong
|
x
|
x
|
x
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getFloat
|
x
|
x
|
x
|
x
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getDouble
|
x
|
x
|
x
|
x
|
x
|
X
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getBigDecimal
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
X
|
X
|
x
|
x
|
x
|
x
|
|
|
|
|
|
|
getBoolean
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
X
|
x
|
x
|
x
|
|
|
|
|
|
|
getString
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
X
|
X
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
getBytes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
X
|
X
|
x
|
|
|
|
getDate
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
x
|
|
|
|
X
|
|
x
|
getTime
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
x
|
|
|
|
|
X
|
x
|
getTimestamp
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
x
|
|
|
|
x
|
x
|
X
|
getAsciiStream
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
X
|
x
|
x
|
x
|
|
|
|
getUnicodeStream
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
X
|
x
|
x
|
x
|
|
|
|
getBinaryStream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
x
|
x
|
X
|
|
|
|
getObject
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
x
|
A more precise explanation is listed here: http://java.sun.com/docs/books/tutorial/jdbc/basics/_retrievingTable.html
.execute() Used for reads or writes [14/21]
.execute() returns true if has a result set
//...
Statement stmt = con.createStatement();
if(stmt.execute(readOrWriteSql))
{
stmt.getResultSet();
}
else
{
int rowsUpdated = stmt.getUpdatedCount();
}
//...
DBTest.java [15/21]
import java.sql.*;
import java.net.*;
import java.util.*;
public class DBTest{
public static void main(String args[]){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSource = "jdbc:odbc:TheDataSourceName";
Connection con = DriverManager.getConnection(dataSource, null, null);
Statement stmt = con.createStatement();
try { stmt.executeUpdate("drop table employee");}
catch (SQLException e){/*do nothing if table does note exist*/ }
stmt.executeUpdate("CREATE table employee " +
"(first varchar(15), last varchar(20), age integer, address varchar(30), " +
" city varchar(20), state varchar(20))");
stmt.executeUpdate("INSERT into employee " +
"(first, last, age, address, city, state) " +
"values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia')");
stmt.executeUpdate("INSERT into employee " +
"(first, last, age, address, city, state) " +
"values ('Arthur', 'Fonzerella', 47, 'Above Mr. C', 'Milwaukee', 'Wisconsin')");
stmt.executeUpdate("INSERT into employee " +
"(first, last, age, address, city, state) " +
"values ('Lucille', 'Ball', 62, '555 Main Street', 'Los Angeles', 'California')");
ResultSet rs = stmt.executeQuery(" Select first, last, address from employee where age > 46 ");
while(rs.next()){
System.out.println("Name: "+rs.getString(1)+" "+
rs.getString(2)+" Address: "+rs.getString(3));
}
}catch(Exception e){System.out.println(e.toString());}
/* !!!!! WARNING !!!!!!!
* in the real world you want to clean up
* system resources in the finally block
* see DBTest2.java below
*/
}
}
DBTest.java
PreparedStatement.java [16/21]
PreparedStatement.java
- Precompiled sql
- Substantial performance gains
- Not as tedious to write
PreparedStatement ps = con.prepareStatement( "update employee set age = ? where last = ?" );
- The question marks (?) indicate a parameter to set before executing
- You can execute over and over again resetting the parameters to different values each time, perhaps based on user entry
-
ps.clearParameters(); // always clear old parameters before executed update again
ps.setObject(1, new Integer(50)); // .setString(int parameterIndexedFrom1toN, Object value);
ps.setString(2, "Duke");
ps.executeUpdate();
Using meta data [17/21]
ResultSetMetaData obtained from a ResultSet
rsmd = rs.getMetaData();
- How many columns?
getColumnCount()
- What is the name of a column?
getColumnName
- What type does a column hold?
getColumnType
- Much more, check api as needed
DataBaseMetaData obtained from the Connection
dbmd = con.getMetaData
.getUrl()
.getMaxConnections()
DBTest2.java [18/21]
import java.sql.*;
import java.net.*;
import java.util.*;
public class DBTest2{
public static void main(String args[]){
Connection con = null;
PreparedStatement ps = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dataSource = "jdbc:odbc:TheDataSourceName";
con = DriverManager.getConnection(dataSource, null, null);
ps = con.prepareStatement( "update employee set age = ? where last = ?" );
ps.clearParameters();
ps.setObject(1, new Integer(50));
ps.setString(2, "Duke");
ps.executeUpdate();
stmt = con.createStatement();
rs = stmt.executeQuery(" Select first, last, address from employee where age > 46 ");
while(rs.next()){
System.out.println("Name: "+rs.getString(1)+" "+
rs.getString(2)+" Address: "+rs.getString(3));
}
}catch(Exception e){System.out.println(e.toString());}
finally
{
try{
if(con != null)
con.close();
if(ps != null)
ps.close();
if(stmt != null)
stmt.close();//also closes result set
}catch(SQLException e1)
{
e1.printStackTrace();
}
}
}
}
DBTest2.java
Most applications are a UI to a DB [19/21]
- What if users need to manipulate DB?
- Make them learn SQL?
- Give them control over what information they see.
- Only display data in ASCII text format?
- Want to write a GUI to handle DB
- Display data in intuitive form (tables)
- Allow searching without SQL knowledge
- Allow updates with minimum of typing
The LIKE SQL command [20/21]
One quick sql command I want to make sure you know for your homeowork
Say you wanted to query the SCHEDULE TABLE from above to give you info on all instructors whose name started with 'S'
SELECT INSTRUCTOR, COURSE, DAY
FROM SCHEDULE
WHERE INSTRUCTOR LIKE 'A%';
The percent sign (%) is used to represent any possible character (number,
letter, or punctuation) or set of characters that might appear after the
"A". To find those people with LastName's ending in "A", use '%A', or if
you wanted the "A" in the middle of the word, try '%A%'.
NOT LIKE displays rows not fitting the given description.
Homework Due Before Class Next Week [21/21]
-Exam 7 Next Week
-Homework 7 Due Before Class