Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- public abstract class AccessDBConnect2 {
- public static Connection connect(){
- String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
- Connection con = null;
- try {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
- con = DriverManager.getConnection(url,"","");
- } catch (Exception e) {
- // Handle exceptions ...
- System.out.println(e.toString());
- System.out.println("A problem accessing the database");
- e.printStackTrace();
- } finally {
- try { if(con!=null) {con.close();} } catch (Exception e) {}
- }
- return con;
- }
- public static void closeConnection(Connection conn){
- try{
- conn.close();
- }catch (Exception e){
- }
- }
- stm = conn.prepareStatement(sql);
- import java.sql.*;
- public class Program2{
- public static void main(String[] args) {
- try{
- // Load the JDBC driver
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
- // Establishing db connection
- Connection conn = AccessDBConnect.connect();
- // Displaying all records from employee file
- System.out.println("Display records of all employees");
- display(conn);
- // Closing the connection
- AccessDBConnect.closeConnection(conn);
- }catch (Exception e){
- System.out.println("Error");
- }
- }
- // Display details of all employees
- public static void display(Connection conn){
- PreparedStatement stm = null;
- // SQL statement
- String sql = "SELECT * FROM Employee";
- ResultSet rs;
- try {
- stm = conn.prepareStatement(sql); // Prepare the SQL statement
- rs = stm.executeQuery(); // Execture the SQL statement
- // Navigate through the ResultSet and print
- while (rs.next()){
- int id = rs.getInt("id");
- String name = rs.getString("name");
- String gender = rs.getString("gender");
- String address = rs.getString("address");
- System.out.println("ID: t t" + id);
- System.out.println("Name: t t" + name);
- System.out.println("Gender: t" + gender);
- System.out.println("Address: t" + address);
- System.out.println(" ");
- }
- // Closing the resultSet
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public void test(){
- int a = "hello";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement