Upload
christiana-harrison
View
227
Download
2
Embed Size (px)
Citation preview
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. To open Data Sources (ODBC),
click Start,
click Control Panel, and then
click Administrative Tools.
Double-click Data Sources
(ODBC).
2. 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 1Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Method 2java -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. // database name = ClassList
2. String url = “jdbc:odbc:ClassList”;
3. String uname = “anonymous”;
4. String pword = “guest”;
5. Connection = DriverManager.getConnection(url,uname,pword);
3. Creating a Database
Ask for a Statement object Execute the SQL statement to create a table.
1. Statement stmt = con.createStatement();2. stmt.execute( "create table Names(“id integer” 3. + “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. String st1 = “insert into Names values (1, ‘Angelia', ‘Jolie');”;
2. 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. column headings
2. 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 Basis of all JDBC exceptions
SQLWarning 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