×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Walter Stroebel
Added: Oct 18, 2017 6:13 AM
Views: 2661
  1.     public Connection Database(String myHostName, String myUserName, String myPassword, String myDatabase,
  2.             final String... startupSQL) throws
  3.             Exception {
  4.         final Connection dbCon = DriverManager.getConnection("jdbc:mysql://" + myHostName + "/?useSSL=false"
  5.                 + "&user=" + myUserName
  6.                 + "&password=" + myPassword);
  7.         try {
  8.             dbCon.setCatalog(myDatabase);
  9.         } catch (Exception any) {
  10.             try (Statement cs = dbCon.createStatement()) {
  11.                 cs.execute("create database " + myDatabase);
  12.             }
  13.             dbCon.setCatalog(myDatabase);
  14.         }
  15.         if (dbCon == null) {
  16.             System.err.println("Connection failed?!?");
  17.             return null;
  18.         } else if (startupSQL != null && startupSQL.length > 0) {
  19.             try {
  20.                 Statement s = dbCon.createStatement();
  21.                 for (String sql : startupSQL) {
  22.                     try {
  23.                         s.execute(sql);
  24.                     } catch (SQLException ex) {
  25.                         System.err.println(sql + " -- " + ex.getMessage());
  26.                     }
  27.                 }
  28.                 s.close();
  29.             } catch (SQLException ex) {
  30.                 ex.printStackTrace();
  31.             }
  32.         }
  33.         return dbCon;
  34.     }
  35.