Download presentation
Presentation is loading. Please wait.
Published byChristiana Harrison Modified over 9 years ago
1
Introduction to JDBC (Java Database Connectivity)
2
Registering ODBC Data Source Before using Java to access to MS Access DB, register the DB as an ODBC data source.
3
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
4
DB Registration Continued 3.Choose Microsoft Access Driver. 4.Click Finish.
5
DB Registration Continued 5.Type the Data Source Name 6.Select the database to use.
6
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
7
1. JDBC-ODBC Bridge Method 1 Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”); Method 2 java -Djdbc.drivers =sun.jdbc.odbc.JdbcOdbcDriver AProgram
8
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);
9
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.
10
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);
11
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;");
12
Class ResultSet 1 The general form of a result set is a table. It has 1. column headings 2. corresponding values Example idfnamelname 1AngelinaJolie 2ArnoldSchwartz
13
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");
14
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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.