Académique Documents
Professionnel Documents
Culture Documents
By Cavalier iT
DATABASE FUNDAMENTALS
Database Database Server Relational Database Keys Normalising SQL Remote Database Access ODBC JDBC
Database server
Software program Manages databases Keeps them organised Provides shared access Physical level and Logical level orgn. Similar to an office assistant.
Relational Database
E.F Codd IBM Mathematician 1960 Tables Columns = type of information Rows = specific records
Keys
Access to info in tables is organized by keys Columns or groups of columns that uniquely identify a row Helps you to decide whether to modify or insert Primary keys Composite keys Foreign keys
Normalising
1 big table ? Many small tables ? Minimize the number of columns Increase data consistency Purpose to remove redundant data & make updation and maintenance easy Trade off between
Data consistency Database size Database performance
SQL
Language for interacting with relational databases
Data Definition Language
Create & Design databases
SQL as a DDL
Data Definition Language
Create & Design databases
CREATE DATABASE <database name> CREATE TABLE <table name> (column defn) COLUMN DEFN. => <Col Name> <Col Type> COLUMN TYPE => char(n); int;float; bit; date; time get() of ResultsSet converts SQL dt to Java dt set() of PreparedStatement do vice versa ALTER TABLE <table name> ADD (column definition) Adds a column where the row values are set to null DROP TABLE <table name>
SQL as a DML
Data Maintenance Language
Updates data
INSERT INTO <table name> VALUES ( , , .) INSERT INTO <table name> (column names) VALUES ( , , .) DELETE FROM <table name> WHERE <condition> UPDATE <table name> SET <column =value> WHERE <condition> ORDER BY <column>
SQL as a DQL
Data Query Language
Retrieves information from database
SELECT <column name> FROM <table name> WHERE <condition> ORDER BY <column>
Goal
Access any data from any application regardless of which DBMS
Solution
Driver inserted between application and DBMS which translates application queries into commands the DBMS understands.
WHY JDBC?
ODBC is a C API
Not Object Oriented Uses Pointers Other dangerous programming constructs
JDBC DRIVERS
4 Categories
JDBC-ODBC Native API
Driver talks in RDBMS native protocol Uses binary code + Java Must be preinstalled
bridge + ODBC
JDBC-Net
Talks in a std. Network protocol to a Database Access Server Database Access Server uses ODBC to speak to RDBMS.
Native Protocol
Talks the vendor specific protocol of the RDBMS
Package
java.sql.*;
SUMMARISING
Import java.sql.* Register the driver Establish the connection Create the statement Execute the query Traverse the resultset Display the results Close the connection
DriverManager class has no constructors All methods are static Some useful methods are:Enumeration getDrivers() Connection getConnection(String url) Connection getConnection(String url, String ID, String pwd) url= jdbc: subprotocol name: DSN
DriverManager Code
import java.sql.*; import java.util.*; class jdbc{ public static void main(String a[]){ try{ Class.forName("com.mysql.jdbc.Driver"); Enumeration drivers=DriverManager.getDrivers(); System.out.println("Available Drivers"); while(drivers.hasMoreElements(){ Driver d=(Driver)drivers.nextElement();
DriverManager Code
System.out.println("Driver "+d.getClass().getName()); System.out.println("Driver "+d.getMajorVersion()); System.out.println("Driver "+d.getMinorVersion()); System.out.println("Driver "+d.jdbcCompliant()); DriverPropertyInfo prop[]=driver.getPropertyInfo("",null); if(props!=null){ for(int i=0; i<prop.length; ++i){ System.out.println("Name "+prop[i].name); System.out.println("Description"+prop[i].description); System.out.println("Value "+prop[i].value); } } }
DriverManager Code
}catch(Exception e){ System.out.println(e); System.exit(0); } }
DatabaseMetaData code
import java.sql.*; import java.util.*; class jdbc1{ public static void main(String a[]){ try{ Class.forName("com.mysql.jdbc.Driver"); Connection c=DriverManager.getConnection("jdbc:odbc:DSN"); DatabaseMetaData meta=c.getMetaData(); System.out.println("Database "+meta.getDatabaseProductName()); System.out.println("Version "+meta.getDatabaseProductVersion); System.out.println("User Name "+meta.getUserName()); c.close() }catch(Exception e){ System.out.println(e); System.exit(0); } } }
ResultSet + executeQuery()
import java.sql.*; import java.util.*; class jdbc2{ public static void main(String a[]){ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c=DriverManager.getConnection(" jdbc:mysql://localhost/test,root,root "); Statement s=c.createStatement(); ResultSet r=s.executeQuery("Select * from <tablename>"); displayResults(r); c.close(); }catch(Exception e){ System.out.println(e); System.exit(0); } }
ResultSet + executeQuery()
static void displayResults(ResultSet rs) throws SQLException{ ResultSetMetaData rmeta=rs.getMetaData(); int no_of_cols=rmeta.getColumnCount(); for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rmeta.getColumnName(i)+" | "); else System.out.print(rmeta.getColumnName(i)); }
ResultSet + executeQuery()
while(rs.next()){ for(int i=1; i<=no_of_cols; ++i){ if(i<no_of_cols) System.out.print(rs.getString(i)+" | "); else System.out.print(rs.getString(i).trim()); } } } }
Prepared Statements
Extends from statement Takes an SQL at creation time Sent to dbms for precompilation Faster than Statement Capable of taking parameters
Creating a PreparedStatement
prepareStatement() method is invoked on the connection object
PreparedStatement updateSales= con.prepareStatement( UPDATE COFFEES SET SALES=? WHERE COF_NAME LIKE ?);
CallableStatement
Used to call stored procedures Is independent of RDBMS syntax
Creating a callablestatement
prepareCall() method of connection object is called CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
Calling a procedure
To call a procedure use one of the execute methods of statement interface ResultSet rs = cs.executeQuery();
Code
Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIV E, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
TRANSACTION PROCESSING
Transaction consists of a group of related database operations. SQL statements that make up the transaction update the database at the same time. Not committed automatically If an error occurs transaction is rolled back
TRANSACTION METHODS
Connection Interface methods for transaction processing are:supportsTransactions() setAutoCommit() commit() rollback() supportsTransactionIsolation(); getTransactionIsolation() setTransactionIsolation()
SUMMARISING
Import java.sql.* Register the driver Establish the connection Create the statement Execute the query Traverse the resultset Display the results Close the connection