Skip to content

Instantly share code, notes, and snippets.

@eirikbakke
Created July 10, 2011 13:40
Show Gist options
  • Save eirikbakke/1074542 to your computer and use it in GitHub Desktop.
Save eirikbakke/1074542 to your computer and use it in GitHub Desktop.
The DatabaseConnector class.
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public final class DatabaseConnector {
private static DatabaseConnector instance;
private static String useMySQL = null;
// Deployment note: Replace with a real server name.
private static final String MYSQL_URI = "jdbc:mysql://somedatabase.com:3306/";
private static final String SQLITE_URI = "jdbc:sqlite:";
private static final String DB_USER = "meetuser";
private static final String DB_PASS = "meetpass";
private Connection connection;
private DatabaseConnector() throws SQLException {
try {
Class.forName("org.sqlite.JDBC");
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
throw new RuntimeException(e);
}
String DB_URI = (useMySQL != null) ? (MYSQL_URI + useMySQL) :
(SQLITE_URI +
new File(System.getProperty("user.home"), "limecat.sqlite").toString());
System.out.println("Using DB " + DB_URI);
connection = DriverManager.getConnection(DB_URI, DB_USER, DB_PASS);
// Don't bother being to transactionally correct for this lab.
connection.setAutoCommit(true);
}
public static DatabaseConnector getInstance() throws SQLException {
if (instance == null)
instance = new DatabaseConnector();
return instance;
}
public Connection getConnection() {
return connection;
}
public boolean isMySQL() {
return useMySQL != null;
}
/* Call this before calling getInstance() to use a remote MySQL server
instead. Everone else has access to this database as well! */
public static void setUseMySQL(String dbName) {
if (instance != null && !dbName.equals(DatabaseConnector.useMySQL)) {
throw new IllegalStateException(
"Can't call setUseMySQL() after getInstance() has been called.");
}
DatabaseConnector.useMySQL = dbName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment