· 8 years ago · Jan 06, 2018, 08:04 AM
1package org.apache.ctakes.examples.pipeline.ExtractLabValues02;
2
3import org.apache.log4j.Logger;
4
5import java.sql.Connection;
6import java.sql.DriverManager;
7import java.sql.SQLException;
8import java.sql.Statement;
9import java.util.Properties;
10
11public class ConnectToDatabase {
12 static private final Logger LOGGER = Logger.getLogger( "ConnectToDatabase" );
13 static private final String dbms = "mysql";
14 static private final String driver = "com.mysql.jdbc.Driver";
15 static private final String dbName = "labreports";
16 static private final String userName= "root";
17 static private final String password = "root";
18 static private final String serverName= "127.0.0.1";
19 static private final int portNumber= 3306;
20
21 public static boolean ignoreSQLException(String sqlState) {
22 if (sqlState == null) {
23 System.out.println("The SQL state is not defined!");
24 return false;
25 }
26 // X0Y32: Jar file already exists in schema
27 if (sqlState.equalsIgnoreCase("X0Y32"))
28 return true;
29 // 42Y55: Table already exists in schema
30 if (sqlState.equalsIgnoreCase("42Y55"))
31 return true;
32 return false;
33 }
34
35 public static void printSQLException(SQLException ex) {
36 for (Throwable e : ex) {
37 if (e instanceof SQLException) {
38 if (ignoreSQLException(((SQLException) e).getSQLState()) == false) {
39 e.printStackTrace(System.err);
40 System.err.println("SQLState: " + ((SQLException) e).getSQLState());
41 System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
42 System.err.println("Message: " + e.getMessage());
43 Throwable t = ex.getCause();
44 while (t != null) {
45 System.out.println("Cause: " + t);
46 t = t.getCause();
47 }
48 }
49 }
50 }
51 }
52
53
54 public static void createDatabase(Connection connArg, String dbNameArg) {
55 try {
56 Statement s = connArg.createStatement();
57 String newDatabaseString =
58 "CREATE DATABASE IF NOT EXISTS " + dbNameArg;
59 // String newDatabaseString = "CREATE DATABASE " + dbName;
60 s.executeUpdate(newDatabaseString);
61 System.out.println("Created database " + dbNameArg);
62 } catch (SQLException e) {
63 printSQLException(e);
64 }
65 }
66
67
68 public static void connectToDatabase() throws SQLException{
69 Connection conn = null;
70 Properties connectionProps = new Properties();
71 connectionProps.put("user", userName);
72 connectionProps.put("password", password);
73
74 String sql_url = "jdbc:" + dbms + "://" + serverName + ":" + portNumber + "/";
75 LOGGER.info("Connecting to database: " + sql_url);
76 conn = DriverManager.getConnection(sql_url, connectionProps);
77
78 createDatabase(conn,dbName);
79 sql_url = "jdbc:" + dbms + "://" + serverName + ":" + portNumber + "/" + dbName;
80 LOGGER.info("Connecting to database: " + sql_url);
81 conn = DriverManager.getConnection(sql_url, connectionProps);
82 LOGGER.info("Connected to database");
83 }
84}