Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4.  
  5. public abstract class AccessDBConnect2 {
  6. public static Connection connect(){
  7. String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
  8. Connection con = null;
  9. try {
  10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  11. String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
  12. con = DriverManager.getConnection(url,"","");
  13. } catch (Exception e) {
  14. // Handle exceptions ...
  15. System.out.println(e.toString());
  16. System.out.println("A problem accessing the database");
  17. e.printStackTrace();
  18. } finally {
  19. try { if(con!=null) {con.close();} } catch (Exception e) {}
  20. }
  21. return con;
  22. }
  23. public static void closeConnection(Connection conn){
  24. try{
  25. conn.close();
  26. }catch (Exception e){
  27.  
  28. }
  29. }
  30.  
  31. stm = conn.prepareStatement(sql);
  32.  
  33. import java.sql.*;
  34. public class Program2{
  35. public static void main(String[] args) {
  36. try{
  37. // Load the JDBC driver
  38. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
  39.  
  40. // Establishing db connection
  41. Connection conn = AccessDBConnect.connect();
  42.  
  43. // Displaying all records from employee file
  44. System.out.println("Display records of all employees");
  45. display(conn);
  46.  
  47. // Closing the connection
  48. AccessDBConnect.closeConnection(conn);
  49. }catch (Exception e){
  50. System.out.println("Error");
  51. }
  52. }
  53.  
  54. // Display details of all employees
  55. public static void display(Connection conn){
  56. PreparedStatement stm = null;
  57. // SQL statement
  58. String sql = "SELECT * FROM Employee";
  59. ResultSet rs;
  60. try {
  61. stm = conn.prepareStatement(sql); // Prepare the SQL statement
  62. rs = stm.executeQuery(); // Execture the SQL statement
  63.  
  64. // Navigate through the ResultSet and print
  65. while (rs.next()){
  66. int id = rs.getInt("id");
  67. String name = rs.getString("name");
  68. String gender = rs.getString("gender");
  69. String address = rs.getString("address");
  70.  
  71. System.out.println("ID: t t" + id);
  72. System.out.println("Name: t t" + name);
  73. System.out.println("Gender: t" + gender);
  74. System.out.println("Address: t" + address);
  75. System.out.println(" ");
  76. }
  77.  
  78. // Closing the resultSet
  79. rs.close();
  80. } catch (SQLException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84.  
  85. public void test(){
  86. int a = "hello";
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement