|
A Sample JDBC Program
Prerequisites
Ensure that following things have been taken care before writing this program:
- Java is installed.
- Classpath & Path variables are appropriately set
Assumptions
This program assumes following:
- You're using a windows machine.
- Database is MS Access.
- A user DSN named jdbcOdbcTest is already created for accessing database. User name & password for accessig DSN are test/test.
Steps
Create a file named MSAccessClient.java and paste following code:
import java.sql.*;
public class MSAccessClient{
public static void main(String[] args){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:jdbcOdbcTest","test", "test");
Statement stmt = con.createStatement();
stmt.execute("create table dummyTable ( myNumber integer )"); // create a table
stmt.execute("insert into dummyTable values(1)"); // insert some data into the table
stmt.execute("select myNumber from dummyTable"); // select the data from the table
ResultSet rs = stmt.getResultSet(); // get any ResultSet that came from our query
if (rs != null) // if rs == null, then there is no ResultSet to view
while ( rs.next() ) // this will step through our data row-by-row
{
/* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("Data from column_name: " + rs.getString(1) );
}
stmt.close(); // close the Statement to let the database know we're done with it
con.close(); // close the Connection to let the database know we're done with it
}catch (Exception err){
System.out.println("ERROR: " + err);
}// end try-catch
} // end main()
}// end class
Now compile above code & execute through a console. This program would create a table named dummyTest with single column myNumber; insert one record into that table; & display (on console) that record by firing a select query against database. You should try some experiments with this class for better understanding. For e.g., this class can be executed only once, because if you execute this class 2nd time; you'll get error. Try to fix that.
|