Problem

Rewrite the example show in Figure 8-4 using Java.

Rewrite the example show in Figure 8-4 using Java.

Step-by-Step Solution

Solution 1

Program Plan:

• Construct the connection string in JDBC for MS Access, while specifying the database name. Ensure that the driver and the database lie in the classpath for JAVA, otherwise the program will not compile.

• Load the jdbc.odbc.JdbcOdbcDriver driver.

• Open the specified database by using Connection class.

• Create a statement for insert query using Statement class and execute it.

• Create a statement for select query and execute it.

• While there is some row to display in result set

o Display the row data.

• Close all open ends.

• Catch any exception and display trace.

Program:

/*****************************************************

* Create a connection with MS Access DB and run an *

* insert and an Select query *

* **************************************************/

//header section

import java.sql.*; //required for Connection class etc.

public class AccessLiteracy {

public static void main(String[] args){

try{

Connect to the specified database and run insert and select query to it.

//construct a new connection with MS Access db

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String database =

"jdbc:odbc:Driver={Microsoft Access Driver (*.accdb)} ;DBQ=literacy.accdb;";

Connection conn = DriverManager.getConnection( database, "", "");

Statement st = conn.createStatement();

Construct insert and select query and execute them.

// enter value into student table

String addNewRow = "INSERT INTO STUDENT VALUES( 10, 3009, 4, 19)";

st.execute(addNewRow);

// get values from student table

String sel = "SELECT * FROM STUDENT";

st.execute(sel);

ResultSet rs = st.getResultSet();

while((rs!=null) && (rs.next())){

System.out.println(rs.getString(2) + " , " + rs.getString(3) + " , " + rs.getString(4)));

}

Close the connection and statement before exiting

// close

st.close();

conn.close();

}

Catch any exception and print trace

catch(Exception ex){

ex.printStackTrace();

}

}

}

Sample Output:

3000 , 2 , 11

3001 , 6 , 12

3002 , 1 , 13

3003 , 3 , 14

3004 , 2 , 15

3005 , 5 , 16

3006 , 8 , 17

3007 , 2 , 18

3009 , 4 , 19

Add your Solution
Textbook Solutions and Answers Search