Advertisement
Guest User

Main class

a guest
Sep 24th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.00 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3. import com.mysql.jdbc.Driver;
  4.  
  5. public class Main {
  6. // JDBC driver name and database URL
  7. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  8. static final String DB_URL = "jdbc:mysql://localhost/lesson";
  9.  
  10. // Database credentials
  11. static final String USER = "root";
  12. static final String PASS = "password";
  13.  
  14. public static void main(String[] args) {
  15. Connection conn = null;
  16. Statement stmt = null;
  17. String sql;
  18.  
  19. try {
  20. //STEP 2: Register JDBC driver
  21. Class.forName(JDBC_DRIVER);
  22.  
  23. //STEP 3: Open a connection
  24. System.out.println("Connecting to database...");
  25. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  26.  
  27. DatabaseThread.DatabaseThreadCallback callback = new DatabaseThread.DatabaseThreadCallback() {
  28. @Override
  29. public void OnRecordsInserted() {
  30. System.out.println("From Main class: OnRecordsInserted() called");
  31. }
  32.  
  33. @Override
  34. public void onError(SQLException ex) {
  35. ex.printStackTrace();
  36. }
  37. };
  38.  
  39. DatabaseThread databaseThread = new DatabaseThread(conn, callback);
  40.  
  41. databaseThread.start();
  42.  
  43. //STEP 4: Execute a query
  44. /* System.out.println("Creating statement...");
  45. stmt = conn.createStatement();
  46.  
  47. sql = "DELETE FROM Employees WHERE id=3";
  48. stmt.executeUpdate(sql);
  49.  
  50. sql = "SELECT id, first, last, age FROM Employees";
  51. ResultSet rs = stmt.executeQuery(sql);
  52.  
  53. //STEP 5: Extract data from result set
  54. while (rs.next()) {
  55. //Retrieve by column name
  56. int id = rs.getInt("id");
  57. int age = rs.getInt("age");
  58. String first = rs.getString("first");
  59. String last = rs.getString("last");
  60.  
  61. //Display values
  62. System.out.print("ID: " + id);
  63. System.out.print(", Age: " + age);
  64. System.out.print(", First: " + first);
  65. System.out.println(", Last: " + last);
  66. }
  67.  
  68. //STEP 6: Clean-up environment
  69. rs.close();
  70. stmt.close();
  71. conn.close();*/
  72. } catch (SQLException se) {
  73. //Handle errors for JDBC
  74. se.printStackTrace();
  75. } catch (Exception e) {
  76. //Handle errors for Class.forName
  77. e.printStackTrace();
  78. } finally {
  79. try {
  80. if (stmt != null)
  81. stmt.close();
  82. } catch (SQLException se2) {
  83. }
  84. try {
  85. if (conn != null)
  86. conn.close();
  87. } catch (SQLException se) {
  88. se.printStackTrace();
  89. }
  90. }
  91. System.out.println("Main class end");
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement