Guest User

Untitled

a guest
Nov 1st, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. import org.apache.commons.io.FileUtils;
  6. import java.io.File;
  7. import java.io.IOException;
  8.  
  9. public class DBtest{
  10. private static int cnt = 0;
  11. public static void main(String[] args) throws SQLException{
  12. System.out.print('u000C');
  13. String db = "test2";
  14. File file = new File(db);
  15.  
  16. Connection conn = connectDB(db);
  17. close(conn);
  18. deleteDB(file);
  19.  
  20. System.exit(0);
  21. }
  22. public static void close(Connection conn){
  23. try{
  24. if (conn != null) conn.close();
  25. System.out.println("Connection closed");
  26. }catch(SQLException e){
  27. System.out.println("connection NOT closed " + e);
  28. System.exit(0);
  29. }
  30. }
  31.  
  32. public static void deleteDB(File file) {
  33. try{
  34. DriverManager.getConnection("jdbc:derby:;shutdown=true");
  35. }catch(SQLException e1){
  36. if(e1.getSQLState().equals("XJ015") && e1.getErrorCode() == 50000){
  37. try{
  38. FileUtils.deleteDirectory(file);
  39. }catch(IOException e2){
  40. System.out.println("FATAL ERROR: folder not deleted " + e2);
  41. System.exit(0);
  42. }
  43. System.out.println("Database shutdown successful");
  44. }else{
  45. System.out.println("FATAL ERROR: Database not shutdown " + e1);
  46. System.exit(0);
  47. }
  48. }
  49. }
  50.  
  51. public static Connection connectDB(String database) {
  52. Connection conn = null;
  53. try{
  54. File db = new File(database);
  55. String URL = "jdbc:derby:" + database + ";create=true";
  56. System.out.println("db exists " + db.exists());
  57.  
  58. conn = DriverManager.getConnection(URL);
  59. System.out.println("Succesfully connected to " + database);
  60. }catch(SQLException e){
  61. System.out.println("FATAL ERROR: from getDB " + e);
  62. System.exit(0);
  63. }
  64. return conn;
  65. }
  66. }
Add Comment
Please, Sign In to add comment