View RSS Feed

My Java Tips

Connectiong To MS Access And Fetching Records

Rate this Entry
by , 11-08-2011 at 06:37 PM (850 Views)
JDBC (Java Database Connectivity) is designed to allow user to use SQL(Structured Query Language) to query databases. JDBC makes our tasks easy as it handles all low-level concerns about particular database types. It allows you to query an Access database with exactly the same source code as with an Oracle database.

JDBC is similar to Microsoft's ODBC with the plus point "Platform Independence". To use JDBC, you need to have database driver to communicate with the database. Normally drivers are installed while installing the database. Like if you install MS SQL Server, Oracle or DB2, database drivers will be installed. To access the database from an application copy the required jar files and proceed.




Java Code:
import java.sql.*;
public class PackageTest {

	// loading driver and making connection with database
	public static Connection getConnection() throws Exception{
		Connection con;
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		// set this to a MS Access DB you have on your machine
		String filename = "c:/mydb.mdb";
		String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
		database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
		// now we can get the connection from the DriverManager
		con = DriverManager.getConnection( database ,"","");
		return con;
	}

	public static void showPackages(Statement stmt) throws Exception
	{
		// displaying contents of Package table

		String query = "select * from package";
		ResultSet result = stmt.executeQuery(query);
		System.out.println("n" +"Contents of table Package");
		System.out.println ("Package ID - Package Name - Duration - Cost");

		while (result.next()) {

			System.out.print(result.getString("pid") + " - ");
			System.out.print(result.getString("pname")+ "- " );
			System.out.print(result.getString("duration")+ " - ");
			System.out.println(result.getString("cost"));

		}
		stmt.close();
	}

		public static void main(String[] args)throws Exception {

		Statement stmt =Fitness.getConnection().createStatement();
		showPackages(stmt);
	}
}

Submit "Connectiong To MS Access And Fetching Records" to Facebook Submit "Connectiong To MS Access And Fetching Records" to Digg Submit "Connectiong To MS Access And Fetching Records" to del.icio.us Submit "Connectiong To MS Access And Fetching Records" to StumbleUpon Submit "Connectiong To MS Access And Fetching Records" to Google

Tags: jdbc, sql Add / Edit Tags
Categories
JDBC

Comments