Advertisement
Guest User

Untitled

a guest
Mar 31st, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. private Connection conn = null;
  2. private Statement st=null;
  3. private ResultSet rs=null;
  4.  
  5. public void setConnection(){
  6. host="localhost";
  7. database="test";
  8. username="testtest";
  9. password="testtest";
  10. String url = "jdbc:mysql://" + host + "/" +database+ "";
  11. try {
  12. Class.forName ("com.mysql.jdbc.Driver");
  13. conn = DriverManager.getConnection (url, username, password);
  14. System.out.println("Succesfuly connected to the database!");
  15.  
  16. } catch(Exception e){
  17. System.out.println("Failed to connect to the database.");
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22. private boolean checkConnection(){
  23. try {
  24. ResultSet cc = st.executeQuery("SELECT 1");
  25. return true;
  26. } catch (SQLException e) {
  27. int n = JOptionPane.showConfirmDialog(
  28. frame,
  29. "The connection was closed, reconnect?",
  30. "Database security measure",
  31. JOptionPane.YES_NO_OPTION);
  32. if(n == JOptionPane.YES_OPTION){
  33. try {
  34. conn.close();
  35. } catch (SQLException e1) {
  36. e1.printStackTrace();
  37. }
  38. setConnection();
  39. } else if ( n == JOptionPane.NO_OPTION){
  40. frame.setVisible(false);
  41. new LoginWindowB();
  42. }
  43. return false;
  44. }
  45. }
  46. btn1.addActionListener(new ActionListener(){
  47. @Override
  48. public void actionPerformed(ActionEvent arg0) {
  49. if(checkConnection()){
  50. try {
  51. rs = st.executeQuery("SELECT * FROM " + selectedTable);
  52. loadData(rs);
  53.  
  54. } catch (SQLException e) {
  55. e.printStackTrace();
  56. }
  57. } else {
  58.  
  59. }
  60. }
  61. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement