]> WPIA git - gigi.git/blob - util/org/cacert/gigi/util/DatabaseManager.java
Database Manager: add optional "user data" sqlscript on creation.
[gigi.git] / util / org / cacert / gigi / util / DatabaseManager.java
1 package org.cacert.gigi.util;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.nio.file.Files;
6 import java.sql.Connection;
7 import java.sql.DriverManager;
8 import java.sql.SQLException;
9 import java.sql.Statement;
10
11 public class DatabaseManager {
12         public static String readFile(File f) throws IOException {
13                 return new String(Files.readAllBytes(f.toPath()));
14         }
15         public static void main(String[] args) throws SQLException,
16                         ClassNotFoundException, IOException {
17                 if (args.length < 4) {
18                         System.err
19                                         .println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
20                         return;
21                 }
22                 run(args);
23         }
24         public static void run(String[] args) throws ClassNotFoundException,
25                         SQLException, IOException {
26                 Class.forName(args[0]);
27                 Connection conn = DriverManager
28                                 .getConnection(args[1], args[2], args[3]);
29                 Statement stmt = conn.createStatement();
30                 addFile(stmt, new File("doc/tableStructure.sql"));
31                 File localData = new File("doc/sampleData.sql");
32                 if (localData.exists()) {
33                         addFile(stmt, localData);
34                 }
35                 stmt.executeBatch();
36                 stmt.close();
37         }
38         private static void addFile(Statement stmt, File f) throws IOException,
39                         SQLException {
40                 String sql = readFile(f);
41                 String[] stmts = sql.split(";");
42                 for (String string : stmts) {
43                         if (!string.trim().equals("")) {
44                                 stmt.addBatch(string);
45                         }
46                 }
47         }
48 }