Introduction to JDBC(Java Database Connectivity).

advertisement
Introduction to JDBC
(Java Database Connectivity)
Registering ODBC Data Source

Before using Java to access to MS
Access DB, register the DB as an ODBC
data source.
DB Registration Continued
To register Names.mdb as an ODBC data
source, use the following steps.
1.
2.
To open Data Sources (ODBC),
click Start,
click Control Panel, and then
click Administrative Tools.
Double-click Data Sources
(ODBC).
Click Add
DB Registration Continued
3.
Choose Microsoft Access
Driver.
4.
Click Finish.
DB Registration Continued
5.
Type the Data Source Name
6.
Select the database to use.
Creating a Database

Step 1:
Load the JDBC-ODBC bridge
 Step 2:
Connect to a data source
 Step 3:
Send SQL statements to create the
table.
 Step 4:
Use the table using SQL
1. JDBC-ODBC Bridge

Method 1
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);

Method 2
java -Djdbc.drivers
=sun.jdbc.odbc.JdbcOdbcDriver AProgram
2. Connect to a data source

JDBC data source (DB) is given in URL.
URLs should be in the following form
jdbc:odbc:data-source-name
Use DriverManager class, to connect to a URL
DriverManager selects the appropriate driver



1.
2.
3.
4.
5.
// database name = ClassList
String url
= “jdbc:odbc:ClassList”;
String uname = “anonymous”;
String pword = “guest”;
Connection
= DriverManager.getConnection(url,uname,pword);
3. Creating a Database

Ask for a Statement object
Execute the SQL statement to create a table.

1.
2.
3.

Statement stmt = con.createStatement();
stmt.execute( "create table Names(“id integer”
+ “fname varchar (32),“
+ “lname varchar(32));" );
In the above,
create table Names( id integer, fname varchar
(32),
lname varchar (20));
is a SQL statement.
4. Insert a Value

After you have created the table, you
can the insert the appropriate values
such as:
1.
2.
String st1 = “insert into Names values (1,
‘Angelia', ‘Jolie');”;
stmt.execute(st1);
4. Getting Information from a
Database


Use executeQuery() method of a
Statement object.
To store the return value of the query,
use the ResultSet class.
1.
ResultSet result = stmt.executeQuery(
"SELECT * from Names;");
Class ResultSet 1


The general form of a result set is a table.
It has
1.
2.

column headings
corresponding values
Example
id
fname
lname
1
Angelina
Jolie
2
Arnold
Schwartz
Class ResultSet 2
Examine the ResultSet by:

Moving to the first row of data.
result.next();

Extracting data from the columns of that row.
String fname = result.getString (“fname");
int cups = result.getInt (“id");
JDBC Exception Types

SQLException


SQLWarning



Basis of all JDBC exceptions
Noncritical error and is not thrown
Extract this messages through the getWarnings
methods of Connection, ResultSet, and Statement
DataTruncation


Special type of SQLWarning
To detect, use instanceof DataTruncation check on
each SQLWarning
Download