Java Code Examples for java.sql.DriverManager

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Openbravo-POS-iPhone-App, under directory /OpenbravoPOS_PDA/src-pda/com/openbravo/pos/pda/dao/.

Source file: BaseJdbcDAO.java

  16 
vote

protected Connection getConnection() throws Exception {
  try {
    Class.forName(properties.getDriverName());
    return DriverManager.getConnection(properties.getUrl(),properties.getDBUser(),properties.getDBPassword());
  }
 catch (  SQLException sqlex) {
    sqlex.printStackTrace();
  }
catch (  Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 

Example 2

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/db/.

Source file: Database.java

  15 
vote

public Connection getDatabase(){
  if (connection == null) {
    try {
      Class.forName(DatabaseOptions.db_driver);
      connection=DriverManager.getConnection(DatabaseOptions.db_uri,DatabaseOptions.db_user,DatabaseOptions.db_pass);
    }
 catch (    Exception e) {
      System.out.println("JAVA_ERROR: failed to load " + DatabaseOptions.db_driver + " driver.");
      e.printStackTrace();
    }
  }
  return connection;
}
 

Example 3

From project activejdbc, under directory /activejdbc/src/test/java/org/javalite/activejdbc/mock/.

Source file: MockDataSource.java

  15 
vote

public Connection getConnection() throws SQLException {
  try {
    Class.forName(driver());
    return DriverManager.getConnection(url(),user(),password());
  }
 catch (  Exception e) {
    throw new SQLException();
  }
}
 

Example 4

From project adbcj, under directory /jdbc/src/main/java/org/adbcj/jdbc/.

Source file: JdbcConnectionManager.java

  15 
vote

public DbFuture<Connection> connect() throws DbException {
  if (isClosed()) {
    throw new DbException("This connection manager is closed");
  }
  final DbFutureConcurrentProxy<Connection> future=new DbFutureConcurrentProxy<Connection>();
  Future<Connection> executorFuture=executorService.submit(new Callable<Connection>(){
    public Connection call() throws Exception {
      try {
        java.sql.Connection jdbcConnection=DriverManager.getConnection(jdbcUrl,properties);
        JdbcConnection connection=new JdbcConnection(JdbcConnectionManager.this,jdbcConnection);
synchronized (lock) {
          if (isClosed()) {
            connection.close(true);
            future.setException(new DbException("Connection manager closed"));
          }
 else {
            connections.add(connection);
            future.setValue(connection);
          }
        }
        return connection;
      }
 catch (      SQLException e) {
        future.setException(new DbException(e));
        e.printStackTrace();
        throw e;
      }
 finally {
        future.setDone();
      }
    }
  }
);
  future.setFuture(executorFuture);
  return future;
}
 

Example 5

From project AdminCmd, under directory /src/main/java/lib/SQL/PatPeter/SQLibrary/.

Source file: MySQL.java

  15 
vote

@Override public void open() throws SQLException {
  initialize();
  String url="";
  url="jdbc:mysql://" + this.hostname + ":"+ this.portnmbr+ "/"+ this.database;
  this.connection=DriverManager.getConnection(url,this.username,this.password);
}
 

Example 6

From project agile, under directory /agile-apps/agile-app-admin/src/main/java/org/headsupdev/agile/app/admin/configuration/.

Source file: SystemConfiguration.java

  15 
vote

private void testSQL(AjaxRequestTarget target){
  String url=sqlUrlField.getDefaultModelObject().toString();
  String username=sqlUsernameField.getModelObject().toString();
  String password=sqlPasswordField.getModelObject().toString();
  boolean result=false;
  try {
    Class.forName(sqlDriver);
    Connection conn=DriverManager.getConnection(url,username,password);
    result=conn != null;
  }
 catch (  Exception e) {
    log.error("Failed SQL test",e);
  }
  sqlTestImage.setBoolean(result);
  target.addComponent(sqlTestImage);
}
 

Example 7

From project akubra, under directory /akubra-txn/src/test/java/org/akubraproject/txn/derby/.

Source file: TestTransactionalStore.java

  15 
vote

/** 
 * Test that things get cleaned up. This runs after all other tests that create or otherwise manipulate blobs.
 */
@Override public void testCleanup() throws Exception {
  super.testCleanup();
  Connection connection=DriverManager.getConnection("jdbc:derby:" + dbDir);
  ResultSet rs=connection.createStatement().executeQuery("SELECT * FROM " + TransactionalStore.NAME_TABLE);
  assertFalse(rs.next(),"unexpected entries in name-map table;");
  rs=connection.createStatement().executeQuery("SELECT * FROM " + TransactionalStore.DEL_TABLE);
  assertFalse(rs.next(),"unexpected entries in deleted-list table;");
}
 

Example 8

From project arastreju, under directory /arastreju.rdb/src/main/java/org/arastreju/bindings/rdb/.

Source file: RdbConnectionProvider.java

  15 
vote

private Connection createCon(){
  Connection con=null;
  try {
    Class.forName(driver);
    con=DriverManager.getConnection(url,user,pass);
    con.setAutoCommit(true);
  }
 catch (  ClassNotFoundException e) {
    System.out.println("cant load driver " + driver);
    logger.debug("Cann't load Driver " + driver);
  }
catch (  SQLException e) {
    e.printStackTrace();
  }
  return con;
}
 

Example 9

From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/sql/.

Source file: ConnectionManager.java

  15 
vote

public static ConnectionManager newInstance(File dir) throws SQLException, ClassNotFoundException {
  Class.forName("org.hsqldb.jdbcDriver");
  String path=dir.getAbsolutePath() + "/index";
  String url="jdbc:hsqldb:file:" + path;
  String user="sa";
  String password="";
  Connection connection=DriverManager.getConnection(url,user,password);
  return new ConnectionManager(connection);
}
 

Example 10

From project azure4j-blog-samples, under directory /Caching/MemcachedWebApp/src/com/persistent/util/.

Source file: DBConnectionUtil.java

  15 
vote

/** 
 * Returns a connection for database.
 * @return
 */
public static Connection getConnection(){
  Connection connection=null;
  try {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    connection=DriverManager.getConnection("jdbc:sqlserver://<server>.database.windows.net;databaseName=Company","<user>@<server>","<password>");
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
catch (  SQLException e) {
    e.printStackTrace();
  }
  return connection;
}
 

Example 11

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/repository/jdbc/util/.

Source file: Connections.java

  15 
vote

/** 
 * Gets a connection.
 * @return a connection
 * @throws SQLException SQL exception
 */
public static Connection getConnection() throws SQLException {
  if (LOGGER.isLoggable(Level.FINEST)) {
    Callstacks.printCallstack(Level.FINEST,new String[]{"org.b3log"},null);
  }
  if ("BoneCP".equals(poolType)) {
    LOGGER.log(Level.FINEST,"Connection pool[createdConns={0}, freeConns={1}, leasedConns={2}]",new Object[]{boneCP.getTotalCreatedConnections(),boneCP.getTotalFree(),boneCP.getTotalLeased()});
    return boneCP.getConnection();
  }
 else   if ("c3p0".equals(poolType)) {
    LOGGER.log(Level.FINEST,"Connection pool[createdConns={0}, freeConns={1}, leasedConns={2}]",new Object[]{c3p0.getNumConnections(),c3p0.getNumIdleConnections(),c3p0.getNumBusyConnections()});
    final Connection ret=c3p0.getConnection();
    ret.setTransactionIsolation(transactionIsolationInt);
    return ret;
  }
 else   if ("none".equals(poolType)) {
    return DriverManager.getConnection(url,userName,password);
  }
  throw new IllegalStateException("Not found database connection pool [" + poolType + "]");
}
 

Example 12

From project BeeQueue, under directory /src/org/beequeue/coordinator/db/.

Source file: DbCoordinator.java

  15 
vote

public Connection connection() throws BeeException {
  try {
    JdbcResourceTracker tracker=TransactionContext.searchResource(JdbcResourceTracker.class,CONNECTION_TRACKER);
    if (tracker == null) {
      Connection conn;
      Class.forName(driver);
      Connection connection=DriverManager.getConnection(url,user,password);
      if (initSql != null) {
        for (        String query : initSql) {
          connection.createStatement().execute(query);
        }
      }
      conn=connection;
      tracker=new JdbcResourceTracker(CONNECTION_TRACKER,conn);
      TransactionContext.register(tracker);
    }
    return tracker.getResource();
  }
 catch (  Exception e) {
    throw new BeeException(e);
  }
}
 

Example 13

From project BetterShop_1, under directory /src/me/jascotty2/lib/mysql/.

Source file: MySQL.java

  15 
vote

/** 
 * Connect/Reconnect using current info
 * @return if can connect & connected
 * @throws Exception
 */
public final boolean connect() throws Exception {
  if (DBconnection == null) {
    if (!checkDependency()) {
      return false;
    }
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    if (isConnected()) {
      disconnect();
    }
    DBconnection=DriverManager.getConnection(String.format("jdbc:mysql://%s:%s/%s?create=true,autoReconnect=true",sql_hostName,sql_portNum,sql_database),sql_username,sql_password);
  }
 else {
    if (DBconnection.isClosed()) {
      DBconnection=DriverManager.getConnection(String.format("jdbc:mysql://%s:%s/%s?create=true,autoReconnect=true",sql_hostName,sql_portNum,sql_database),sql_username,sql_password);
    }
  }
  return true;
}
 

Example 14

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCP.java

  15 
vote

/** 
 * Drops a driver from the DriverManager's list. 
 */
public void unregisterDriver(){
  logger.info("Unregistering driver.");
  String jdbcURL=this.config.getJdbcUrl();
  if (this.config.isDeregisterDriverOnClose() && (jdbcURL != null)) {
    try {
      DriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL));
    }
 catch (    SQLException e) {
      logger.info("Unregistering driver failed.",e);
    }
  }
}
 

Example 15

From project Catacombs, under directory /src/net/steeleyes/catacombs/.

Source file: CatSQL.java

  15 
vote

public CatSQL(String p){
  path=p;
  try {
    Class.forName("org.sqlite.JDBC");
    conn=DriverManager.getConnection("jdbc:sqlite:" + path);
    conn.setAutoCommit(true);
  }
 catch (  Exception e) {
    System.err.println("[Catacombs] Sqlite error: " + e.getMessage());
  }
}
 

Example 16

From project caustic, under directory /console/src/net/caustic/database/.

Source file: JDBCSqliteConnection.java

  15 
vote

/** 
 * Open  {@link JDBCSqliteConnection} using org.sqlite.JDBC.
 */
@Override public void open() throws ConnectionException {
  try {
    Class.forName("org.sqlite.JDBC");
    connection=DriverManager.getConnection(connectionPath);
    connection.setAutoCommit(false);
    tableExistsStmt=connection.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name=?;");
  }
 catch (  SQLException e) {
    throw new SQLConnectionException(e);
  }
catch (  ClassNotFoundException e) {
    throw new SQLConnectionException(e);
  }
}
 

Example 17

From project ChessCraft, under directory /src/main/java/me/desht/chesscraft/results/.

Source file: ResultsDB.java

  15 
vote

ResultsDB() throws ClassNotFoundException, SQLException {
  Class.forName("org.sqlite.JDBC");
  File dbFile=new File(DirectoryStructure.getResultsDir(),"results.db");
  connection=DriverManager.getConnection("jdbc:sqlite:" + dbFile.getAbsolutePath());
  setupTables();
}
 

Example 18

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Module.java

  15 
vote

/** 
 * Return a new connection to the SQL database. This will return always the same instance, so if you close it, you're doomed. If connection failed, null will be returned (which can happen if the jdbc libraries are not found)
 * @return A connection to the database or null.
 */
public Connection getSQLConnection(){
  if (mSQLConnection != null)   return mSQLConnection;
  if (mSQLFailed)   return null;
  try {
    Class.forName("org.sqlite.JDBC");
    String fnBase="raw/report.db";
    String fn=mDoc.getOutDir() + fnBase;
    File f=new File(fn);
    f.delete();
    mSQLConnection=DriverManager.getConnection("jdbc:sqlite:" + fn);
    if (mSQLConnection != null) {
      mSQLConnection.setAutoCommit(false);
      addHeaderLine("Note: SQLite report database created as " + fnBase);
    }
  }
 catch (  Throwable t) {
    printErr(2,"Cannot make DB connection: " + t);
    mSQLFailed=true;
  }
  return mSQLConnection;
}
 

Example 19

From project CloudReports, under directory /src/main/java/cloudreports/database/.

Source file: Database.java

  15 
vote

/** 
 * Establishes a connection with the current active database.
 * @see #connection
 * @since   1.0
 */
private static void establishConnection(){
  try {
    Class.forName("org.sqlite.JDBC");
    connection=DriverManager.getConnection("jdbc:sqlite:db/" + HibernateUtil.getActiveDatabase() + ".cre");
  }
 catch (  SQLException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
catch (  ClassNotFoundException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
}
 

Example 20

From project codjo-broadcast, under directory /codjo-broadcast-common/src/test/java/net/codjo/broadcast/common/computed/.

Source file: ConstantFieldTest.java

  15 
vote

public void test_compute() throws Exception {
  ConstantField field=new ConstantField("COL_CST",Types.VARCHAR,"","constante");
  FakeDriver.getDriver().pushUpdateConstraint("update " + ctxt.getComputedTableName() + " set COL_CST = constante");
  field.compute(ctxt,DriverManager.getConnection("jdbc:fakeDriver"));
  assertTrue(FakeDriver.getDriver().isUpdateConstraintEmpty());
}
 

Example 21

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: ConnectionManager.java

  15 
vote

/** 
 * Adds a feature to the NewConnection attribute of the ConnectionManager object
 * @throws SQLException         Description of Exception
 * @throws NullPointerException TODO
 */
void addNewConnection() throws SQLException {
  Connection con=DriverManager.getConnection(dbUrl,dbProps);
  if (con == null) {
    throw new NullPointerException("DriverManager retourne une connection null");
  }
  if (catalog != null) {
    con.setCatalog(catalog);
  }
  allConnections.add(con);
  unusedConnections.push(con);
}
 

Example 22

From project Cooking-to-Goal, under directory /lib/db-derby-10.7.1.1-bin/demo/programs/nserverdemo/.

Source file: NsSampleClientThread.java

  15 
vote

/** 
 * gets a database connection If the dbUrl is trying to connect to the Derby NetNsSampleWork server using JCC then the jcc driver must be already loaded before calling this method, else there will be an error return jcc connection if no error, else null
 */
public Connection getConnection(String dbUrl,Properties properties){
  Connection conn=null;
  try {
    pw.println("[NsSampleWork] Thread id - " + thread_id + "; requests database connection, dbUrl ="+ dbUrl);
    conn=DriverManager.getConnection(dbUrl,properties);
  }
 catch (  Exception e) {
    System.out.println("[NsSampleWork] Thread id - " + thread_id + "; failed to get database connection. Exception thrown:");
    e.printStackTrace();
  }
  return conn;
}
 

Example 23

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/creator/.

Source file: DBCreator.java

  15 
vote

/** 
 * Open connection to the DB.
 * @param connectionProperties connection properties
 * @return connection
 * @throws DBCreatorException if can't establish connection to DB
 */
private Connection openConnection() throws DBCreatorException {
  Connection conn=null;
  try {
    ClassLoading.forName(connectionProperties.get(DRIVER_NAME),this);
    conn=SecurityHelper.doPrivilegedSQLExceptionAction(new PrivilegedExceptionAction<Connection>(){
      public Connection run() throws Exception {
        return DriverManager.getConnection(serverUrl,connectionProperties.get(USERNAME),connectionProperties.get(PASSWORD));
      }
    }
);
    return conn;
  }
 catch (  SQLException e) {
    throw new DBCreatorException("Can't establish the JDBC connection to database " + serverUrl,e);
  }
catch (  ClassNotFoundException e) {
    throw new DBCreatorException("Can't load the JDBC driver " + connectionProperties.get(DRIVER_NAME),e);
  }
}
 

Example 24

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityServer.java

  15 
vote

public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
  prop=new Properties();
  prop.load(new FileInputStream("ferryinpres.properties"));
  String MYSQL_HOST=prop.getProperty("MYSQL_HOST");
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  ServerSocket server_sock=new ServerSocket(Integer.parseInt(prop.getProperty("IDENTITY_PORT")));
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  String url="jdbc:mysql://" + MYSQL_HOST + "/frontier";
  Connection con=DriverManager.getConnection(url,"ferryinpres","pass");
  ExecutorService pool=Executors.newFixedThreadPool(12);
  for (; ; ) {
    System.out.println("En attente d'un nouveau client");
    Socket sock=server_sock.accept();
    System.out.println("Nouveau client");
    pool.execute(new ServerThread(sock,con));
  }
}
 

Example 25

From project CraftCommons, under directory /src/main/java/com/craftfire/commons/managers/.

Source file: DataManager.java

  15 
vote

public void connect(){
  if (this.url == null) {
    this.setURL();
  }
  if (this.con != null && this.isConnected()) {
    return;
  }
  try {
switch (this.datatype) {
case MYSQL:
      Class.forName("com.mysql.jdbc.Driver");
    this.con=DriverManager.getConnection(this.url,this.username,this.password);
  break;
case H2:
Class.forName("org.h2.Driver");
this.con=DriverManager.getConnection(this.url,this.username,this.password);
break;
}
}
 catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
 

Example 26

From project datavalve, under directory /datavalve-hibernate/src/test/java/org/fluttercode/datavalve/provider/hibernate/.

Source file: HibernateDatasetTest.java

  15 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  try {
    Class.forName("org.hsqldb.jdbcDriver");
    connection=DriverManager.getConnection("jdbc:hsqldb:mem:unit-testing-jpa","sa","");
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    fail("Exception during HSQL database startup.");
  }
  AnnotationConfiguration cfg=new AnnotationConfiguration();
  cfg.addAnnotatedClass(Order.class);
  cfg.addAnnotatedClass(Person.class);
  sessionFactory=cfg.configure().buildSessionFactory();
  session=sessionFactory.openSession();
  generateTestData();
  dataset=buildQueryDatasetx();
}
 

Example 27

From project db2triples, under directory /src/main/java/net/antidot/sql/model/core/.

Source file: SQLConnector.java

  15 
vote

/** 
 * Try to connect a database and returns current connection.
 * @param userName
 * @param password
 * @param url
 * @param driver
 * @param database
 * @return
 * @throws SQLException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
static public Connection connect(String userName,String password,String url,DriverType driver,String database) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
  log.info("[SQLConnection:extractDatabase] Try to connect " + url + database+ " with "+ driver);
  Class.forName(driver.getDriverName()).newInstance();
  Connection conn=DriverManager.getConnection(url + database,userName,password);
  log.info("[SQLConnection:extractDatabase] Database connection established.");
  return conn;
}
 

Example 28

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/jdbc/.

Source file: JDBCAppender.java

  15 
vote

/** 
 * Override this to link with your connection pooling system. By default this creates a single connection which is held open until the object is garbage collected.
 */
protected Connection getConnection() throws SQLException {
  if (!DriverManager.getDrivers().hasMoreElements())   setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
  if (connection == null) {
    connection=DriverManager.getConnection(databaseURL,databaseUser,databasePassword);
  }
  return connection;
}
 

Example 29

From project dolphin, under directory /dolphinmaple/src/com/tan/biz/.

Source file: DB.java

  15 
vote

public Connection getConnection() throws Exception {
  try {
    Class.forName(CLASSNAME);
    conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
    conn.setAutoCommit(false);
  }
 catch (  ClassNotFoundException e) {
    throw new Exception("??????????");
  }
catch (  SQLException e) {
    throw new Exception("??????????");
  }
  return conn;
}
 

Example 30

From project EasyBan, under directory /src/uk/org/whoami/easyban/datasource/.

Source file: HSQLDataSource.java

  15 
vote

@Override final protected synchronized void connect() throws SQLException, ClassNotFoundException {
  Class.forName("org.hsqldb.jdbc.JDBCDriver");
  ConsoleLogger.info("HSQLDB driver loaded");
  con=DriverManager.getConnection("jdbc:hsqldb:file:" + path,"SA","");
  ConsoleLogger.info("Connected to Database");
}
 

Example 31

From project EasySOA, under directory /samples/Talend-Airport-Service/SimpleProvider_0.1/SimpleProvider/src/routines/system/.

Source file: SharedDBConnection.java

  15 
vote

private synchronized Connection getConnection(String dbDriver,String url,String userName,String password,String dbConnectionName) throws ClassNotFoundException, SQLException {
  if (DEBUG) {
    Set<String> keySet=sharedConnections.keySet();
    System.out.print("SharedDBConnection, current shared connections list is:");
    for (    String key : keySet) {
      System.out.print(" " + key);
    }
    System.out.println();
  }
  Connection connection=sharedConnections.get(dbConnectionName);
  if (connection == null) {
    if (DEBUG) {
      System.out.println("SharedDBConnection, can't find the key:" + dbConnectionName + " "+ "so create a new one and share it.");
    }
    Class.forName(dbDriver);
    connection=DriverManager.getConnection(url,userName,password);
    sharedConnections.put(dbConnectionName,connection);
  }
 else   if (connection.isClosed()) {
    if (DEBUG) {
      System.out.println("SharedDBConnection, find the key: " + dbConnectionName + " "+ "But it is closed. So create a new one and share it.");
    }
    connection=DriverManager.getConnection(url,userName,password);
    sharedConnections.put(dbConnectionName,connection);
  }
 else {
    if (DEBUG) {
      System.out.println("SharedDBConnection, find the key: " + dbConnectionName + " "+ "it is OK.");
    }
  }
  return connection;
}
 

Example 32

From project ehour, under directory /eHour-persistence/src/test/java/net/rrm/ehour/persistence/dbunit/.

Source file: ExtractDataset.java

  15 
vote

public static void main(String[] args) throws Exception {
  Class.forName("com.mysql.jdbc.Driver");
  Connection jdbcConnection=DriverManager.getConnection("jdbc:mysql://127.0.0.1/ehour_08","root","root");
  IDatabaseConnection connection=new DatabaseConnection(jdbcConnection);
  QueryDataSet partialDataSet=new QueryDataSet(connection);
  partialDataSet.addTable("AUDIT");
  FlatXmlDataSet.write(partialDataSet,new FileOutputStream("src/test/resources/test-dataset-20081112.xml"));
  System.out.println("Dataset written");
}
 

Example 33

From project eik, under directory /plugins/info.evanchik.karaf.app/src/main/java/org/apache/felix/karaf/main/.

Source file: DefaultJDBCLock.java

  15 
vote

/** 
 * getConnection - Obtain connection to database via jdbc driver.
 * @throws Exception
 * @param driver, the JDBC driver class.
 * @param url, url to data source.
 * @param username, user to access data source.
 * @param password, password for specified user.
 * @return connection, null returned if conenction fails.
 */
private Connection getConnection(String driver,String url,String username,String password) throws Exception {
  Connection conn=null;
  try {
    Class.forName(driver);
    if (url.startsWith("jdbc:derby:")) {
      conn=DriverManager.getConnection(url + ";create=true",username,password);
    }
 else {
      conn=DriverManager.getConnection(url,username,password);
    }
  }
 catch (  Exception e) {
    LOG.severe("Error occured while setting up JDBC connection: " + e);
    throw e;
  }
  return conn;
}
 

Example 34

From project elasticsearch-river-jdbc, under directory /src/main/java/org/elasticsearch/river/jdbc/.

Source file: SQLService.java

  15 
vote

/** 
 * Get JDBC connection
 * @param driverClassName
 * @param jdbcURL
 * @param user
 * @param password
 * @return the connection
 * @throws ClassNotFoundException
 * @throws SQLException
 */
public Connection getConnection(final String driverClassName,final String jdbcURL,final String user,final String password,boolean readOnly) throws ClassNotFoundException, SQLException {
  Class.forName(driverClassName);
  this.connection=DriverManager.getConnection(jdbcURL,user,password);
  connection.setReadOnly(readOnly);
  connection.setAutoCommit(false);
  return connection;
}
 

Example 35

From project empire-db, under directory /empire-db/src/test/java/org/apache/empire/db/.

Source file: IntegerTest.java

  15 
vote

private static Connection getJDBCConnection(SampleConfig config){
  Connection conn=null;
  LOGGER.info("Connecting to Database'" + config.jdbcURL + "'");
  try {
    Class.forName(config.jdbcClass).newInstance();
    conn=DriverManager.getConnection(config.jdbcURL,config.jdbcUser,config.jdbcPwd);
    LOGGER.info("Connected successfully");
    conn.setAutoCommit(false);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  return conn;
}
 

Example 36

From project encog-java-core, under directory /src/main/java/org/encog/ml/data/buffer/codec/.

Source file: SQLCODEC.java

  15 
vote

/** 
 * Construct a SQL dataset. A connection will be opened, this connection will be closed when the close method is called.
 * @param theSQL The SQL command to execute.
 * @param theInputSize The size of the input data.
 * @param theIdealSize The size of the ideal data.
 * @param theDriver The driver to use.
 * @param theURL The database connection URL.
 * @param theUID The database user id.
 * @param thePWD The database password.
 */
public SQLCODEC(final String theSQL,final int theInputSize,final int theIdealSize,final String theDriver,final String theURL,final String theUID,final String thePWD){
  this.inputSize=theInputSize;
  this.idealSize=theIdealSize;
  this.closeConnection=true;
  try {
    Class.forName(theDriver);
    if ((theUID == null) || (thePWD == null)) {
      this.connection=DriverManager.getConnection(theURL);
    }
 else {
      this.connection=DriverManager.getConnection(theURL,theUID,thePWD);
    }
    this.statement=this.connection.prepareStatement(theSQL);
  }
 catch (  final ClassNotFoundException e) {
    throw new MLDataError(e);
  }
catch (  final SQLException e) {
    throw new MLDataError(e);
  }
}
 

Example 37

From project Enterprise-Application-Samples, under directory /CCA/PushApp/src/eclserver/db/.

Source file: ConnectionFactory.java

  15 
vote

private boolean createDatabase(){
  boolean bCreated=false;
  dbConnection=null;
  String dbUrl=getDatabaseUrl();
  dbProperties.put("create","true");
  try {
    dbConnection=DriverManager.getConnection(dbUrl,dbProperties);
    bCreated=createTables(dbConnection);
  }
 catch (  SQLException ex) {
    System.out.println("SQLEXCEPTION CREATE DATABASE: " + ex.getMessage());
  }
  dbProperties.remove("create");
  return bCreated;
}
 

Example 38

From project excilys-bank, under directory /excilys-bank-dao-impl/src/main/java/com/excilys/ebi/bank/jdbc/.

Source file: DriverUnregistringDataSource.java

  15 
vote

@Override public void close(){
  super.close();
  Driver driver;
  try {
    driver=DriverManager.getDriver(getUrl());
    DriverManager.deregisterDriver(driver);
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
}
 

Example 39

From project fairy, under directory /fairy-core/src/main/java/com/mewmew/fairy/v1/book/.

Source file: Sql.java

  15 
vote

private void runSql(String driver,String jdbcUrl,String user,String password) throws SQLException, IOException {
  if (!StringUtils.isEmpty(driver)) {
    try {
      DriverManager.registerDriver((Driver)Class.forName(driver).newInstance());
    }
 catch (    Exception e) {
    }
  }
  Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
  runSql(connection,query);
}
 

Example 40

From project flume, under directory /flume-ng-channels/flume-jdbc-channel/src/main/java/org/apache/flume/channel/jdbc/impl/.

Source file: JdbcChannelProviderImpl.java

  15 
vote

@Override public void close(){
  try {
    connectionPool.close();
  }
 catch (  Exception ex) {
    throw new JdbcChannelException("Unable to close connection pool",ex);
  }
  if (databaseType.equals(DatabaseType.DERBY) && driverClassName.equals(EMBEDDED_DERBY_DRIVER_CLASSNAME)) {
    if (connectUrl.startsWith("jdbc:derby:")) {
      int index=connectUrl.indexOf(";");
      String baseUrl=null;
      if (index != -1) {
        baseUrl=connectUrl.substring(0,index + 1);
      }
 else {
        baseUrl=connectUrl + ";";
      }
      String shutDownUrl=baseUrl + "shutdown=true";
      LOGGER.debug("Attempting to shutdown embedded Derby using URL: " + shutDownUrl);
      try {
        DriverManager.getConnection(shutDownUrl);
      }
 catch (      SQLException ex) {
        if (ex.getErrorCode() != 45000) {
          throw new JdbcChannelException("Unable to shutdown embedded Derby: " + shutDownUrl + " Error Code: "+ ex.getErrorCode(),ex);
        }
        LOGGER.info("Embedded Derby shutdown raised SQL STATE " + "45000 as expected.");
      }
    }
 else {
      LOGGER.warn("Even though embedded Derby drvier was loaded, the connect " + "URL is of an unexpected form: " + connectUrl + ". Therfore no "+ "attempt will be made to shutdown embedded Derby instance.");
    }
  }
  dataSource=null;
  txFactory=null;
  schemaHandler=null;
}
 

Example 41

From project gatein-toolbox, under directory /sqlman/src/test/java/org/sqlman/.

Source file: SQLTestCase.java

  15 
vote

@Test @BMScript(dir="src/main/resources",value="sqlman") public void testSimple() throws Exception {
  System.setProperty("sqlman.pkgs","org.sqlman");
  SQLMan sqlman=SQLMan.getInstance();
  assertEquals(-1,sqlman.getCountValue("jdbc",0));
  assertEquals(-1,sqlman.getCountValue("jdbcquery",0));
  assertEquals(-1,sqlman.getCountValue("jdbcupdate",0));
  Connection conn=DriverManager.getConnection("jdbc:hsqldb:mem:test","sa","");
  PreparedStatement ps=conn.prepareStatement("CREATE TABLE FOO ( POUET INTEGER )");
  ps.executeUpdate();
  assertEquals(-1,sqlman.getCountValue("jdbc",0));
  assertEquals(-1,sqlman.getCountValue("jdbcquery",0));
  assertEquals(1,sqlman.getCountValue("jdbcupdate",0));
  PreparedStatement ps2=conn.prepareStatement("INSERT INTO FOO (POUET) VALUES (?)");
  ps2.setInt(1,50);
  ps2.execute();
  assertEquals(1,sqlman.getCountValue("jdbc",0));
  assertEquals(-1,sqlman.getCountValue("jdbcquery",0));
  assertEquals(1,sqlman.getCountValue("jdbcupdate",0));
  PreparedStatement ps3=conn.prepareStatement("SELECT POUET FROM FOO");
  ResultSet rs=ps3.executeQuery();
  assertTrue(rs.next());
  assertEquals(50,rs.getInt(1));
  assertEquals(1,sqlman.getCountValue("jdbc",0));
  assertEquals(1,sqlman.getCountValue("jdbcquery",0));
  assertEquals(1,sqlman.getCountValue("jdbcupdate",0));
  ps.close();
  long v1=sqlman.getCountValue("loadbundle",0);
  ResourceBundle bundle=ResourceBundle.getBundle("bundle",Locale.ENGLISH);
  assertNotNull(bundle);
  long v2=sqlman.getCountValue("loadbundle",0);
  assertEquals(2,v2 - v1);
}
 

Example 42

From project gemini.web.gemini-web-container, under directory /org.eclipse.gemini.web.tomcat/src/main/java/org/eclipse/gemini/web/tomcat/internal/loading/.

Source file: BundleWebappClassLoader.java

  15 
vote

/** 
 * Clear references.
 */
protected void clearReferences(){
  Enumeration<Driver> drivers=DriverManager.getDrivers();
  while (drivers.hasMoreElements()) {
    Driver driver=drivers.nextElement();
    if (driver.getClass().getClassLoader() == this) {
      try {
        DriverManager.deregisterDriver(driver);
      }
 catch (      SQLException e) {
        log.warn("SQL driver deregistration failed",e);
      }
    }
  }
  IntrospectionUtils.clear();
  org.apache.juli.logging.LogFactory.release(this);
  java.beans.Introspector.flushCaches();
}
 

Example 43

From project GeoBI, under directory /webapp/src/main/java/com/c2c/query/.

Source file: AbstractQuery.java

  15 
vote

private OlapConnection connect() throws IOException {
  try {
    Class.forName("mondrian.olap4j.MondrianOlap4jDriver");
    Connection connection=DriverManager.getConnection(connectionParams);
    return connection.unwrap(OlapConnection.class);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 44

From project gmc, under directory /src/org.gluster.storage.management.gateway/src/org/gluster/storage/management/gateway/utils/.

Source file: DBUtil.java

  15 
vote

public static void shutdownDerby(){
  try {
    DriverManager.getConnection("jdbc:derby:;shutdown=true");
  }
 catch (  Exception e) {
    if (e instanceof SQLException) {
      SQLException se=(SQLException)e;
      if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState())))) {
        logger.info("Derby shut down normally");
      }
 else {
        logger.error("Derby did not shut down normally!" + inspectSQLException(se),se);
      }
    }
 else {
      logger.error("Derby did not shut down normally! [" + e.getMessage() + "]",e);
    }
  }
  System.gc();
}
 

Example 45

From project gora, under directory /gora-sql/src/test/java/org/apache/gora/sql/.

Source file: GoraSqlTestDriver.java

  15 
vote

@SuppressWarnings("unused") private Connection createConnection(String driverClassName,String url) throws Exception {
  ClassLoadingUtils.loadClass(driverClassName);
  Connection connection=DriverManager.getConnection(url);
  connection.setAutoCommit(false);
  return connection;
}
 

Example 46

From project guj.com.br, under directory /src/net/jforum/.

Source file: SimpleConnection.java

  15 
vote

/** 
 * @see net.jforum.Connection#getConnection()
 */
public Connection getConnection(){
  try {
    return DriverManager.getConnection(SystemGlobals.getValue(ConfigKeys.DATABASE_CONNECTION_STRING));
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new DatabaseException(e);
  }
}
 

Example 47

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/dialect/.

Source file: StandardDialect.java

  15 
vote

private Driver findDriver(){
  String url=String.format("jdbc:%s:test",this.vendorPattern());
  List<Driver> drivers=Collections.list(DriverManager.getDrivers());
  for (  Driver driver : drivers) {
    try {
      if (driver.acceptsURL(url)) {
        return driver;
      }
    }
 catch (    SQLException e) {
    }
  }
  return null;
}
 

Example 48

From project harmony, under directory /harmony.adapter.thin/src/main/java/org/opennaas/extensions/idb/da/thin/persistence/.

Source file: DbConnectionManager.java

  15 
vote

/** 
 * Returns a connection to the database.
 * @return the connection
 */
public static Connection getConnection(){
  try {
    con=DriverManager.getConnection(URL,USERNAME,PASSWORD);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return con;
}
 

Example 49

From project HBql, under directory /src/test/java/org/apache/hadoop/hbase/hbql/.

Source file: ExamplesTest.java

  15 
vote

public void jdbc1() throws SQLException, ClassNotFoundException {
  Class.forName("org.apache.hadoop.hbase.jdbc.Driver");
  Connection conn=DriverManager.getConnection("jdbc:hbql;maxtablerefs=10");
  Connection conn2=DriverManager.getConnection("jdbc:hbql;maxtablerefs=10;hbase.master=192.168.1.90:60000");
  Configuration config=HBaseConfiguration.create();
  Connection conn3=org.apache.hadoop.hbase.jdbc.Driver.getConnection("jdbc:hbql;maxtablerefs=10",config);
  Statement stmt=conn.createStatement();
  stmt.execute("CREATE TABLE table12 (f1(), f3()) IF NOT tableexists('table12')");
  stmt.execute("CREATE TEMP MAPPING sch9 FOR TABLE table12" + "(" + "keyval key, "+ "f1 ("+ "    val1 string alias val1, "+ "    val2 string alias val2 "+ "), "+ "f3 ("+ "    val1 int alias val5, "+ "    val2 int alias val6 "+ "))");
  ResultSet rs=stmt.executeQuery("select * from sch9");
  while (rs.next()) {
    int val5=rs.getInt("val5");
    int val6=rs.getInt("val6");
    String val1=rs.getString("val1");
    String val2=rs.getString("val2");
    System.out.print("val5: " + val5);
    System.out.print(", val6: " + val6);
    System.out.print(", val1: " + val1);
    System.out.println(", val2: " + val2);
  }
  rs.close();
  stmt.execute("DISABLE TABLE table12");
  stmt.execute("DROP TABLE table12");
  stmt.close();
  conn.close();
}
 

Example 50

From project Hesperid, under directory /server/src/main/java/ch/astina/hesperid/installer/web/services/.

Source file: InstallationManager.java

  15 
vote

public void testDatabaseConnection(String databaseUrl,String databaseUser,String databaseSecret) throws Exception {
  Connection con=null;
  try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con=DriverManager.getConnection(databaseUrl,databaseUser,databaseSecret);
    if (!con.isClosed()) {
      logger.info("Successfully connected to " + "MySQL server using TCP/IP...");
    }
  }
 catch (  Exception e) {
    throw e;
  }
 finally {
    if (con != null) {
      try {
        con.close();
      }
 catch (      Exception ex) {
        logger.error("Error while closing connection");
      }
    }
  }
}
 

Example 51

From project hiho, under directory /src/co/nubetech/apache/hadoop/.

Source file: DBConfiguration.java

  15 
vote

/** 
 * Returns a connection object o the DB 
 * @throws ClassNotFoundException 
 * @throws SQLException 
 */
public Connection getConnection() throws ClassNotFoundException, SQLException {
  Class.forName(conf.get(DBConfiguration.DRIVER_CLASS_PROPERTY));
  if (conf.get(DBConfiguration.USERNAME_PROPERTY) == null) {
    return DriverManager.getConnection(conf.get(DBConfiguration.URL_PROPERTY));
  }
 else {
    return DriverManager.getConnection(conf.get(DBConfiguration.URL_PROPERTY),conf.get(DBConfiguration.USERNAME_PROPERTY),conf.get(DBConfiguration.PASSWORD_PROPERTY));
  }
}
 

Example 52

From project Hotel-Management_MINF10-HCM, under directory /HotelManagement/src/main/java/connect/sqlite/.

Source file: ConnectData.java

  15 
vote

public boolean connect(){
  try {
    String url="jdbc:sqlite:" + System.getProperty("user.dir") + "\\Database\\Hotel.s3db";
    System.out.println(url);
    Class.forName("org.sqlite.JDBC");
    conn=DriverManager.getConnection(url);
    if (conn != null)     System.out.println("Connected!");
    return true;
  }
 catch (  Exception e) {
    System.err.println("Fail Connected!");
  }
  return false;
}
 

Example 53

From project iciql, under directory /src/com/iciql/util/.

Source file: JdbcUtils.java

  15 
vote

/** 
 * Open a new database connection with the given settings.
 * @param driver the driver class name
 * @param url the database URL
 * @param prop the properties containing at least the user name and password
 * @return the database connection
 */
public static Connection getConnection(String driver,String url,Properties prop) throws SQLException {
  if (StringUtils.isNullOrEmpty(driver)) {
    JdbcUtils.load(url);
  }
 else {
    Class<?> d=Utils.loadClass(driver);
    if (java.sql.Driver.class.isAssignableFrom(d)) {
      return DriverManager.getConnection(url,prop);
    }
 else     if (javax.naming.Context.class.isAssignableFrom(d)) {
      try {
        Context context=(Context)d.newInstance();
        DataSource ds=(DataSource)context.lookup(url);
        String user=prop.getProperty("user");
        String password=prop.getProperty("password");
        if (StringUtils.isNullOrEmpty(user) && StringUtils.isNullOrEmpty(password)) {
          return ds.getConnection();
        }
        return ds.getConnection(user,password);
      }
 catch (      SQLException e) {
        throw e;
      }
catch (      Exception e) {
        throw new SQLException("Failed to get connection for " + url,e);
      }
    }
 else {
      return DriverManager.getConnection(url,prop);
    }
  }
  return DriverManager.getConnection(url,prop);
}
 

Example 54

From project ihtika, under directory /Sources/Bundles/I_InternalFunctions/src/main/java/ihtika2/i_internalfunctions/service/.

Source file: InternalFunctions.java

  15 
vote

@Override public void initDB(){
  try {
    DriverManager.registerDriver(new JDBCDriver());
    Ini.conn=DriverManager.getConnection("jdbc:hsqldb:file:Db/pages");
    Ini.stmt=Ini.conn.createStatement();
    Ini.rs=null;
    Ini.rs=Ini.stmt.executeQuery("select count(1) as qwe from " + " information_schema.system_tables " + "where table_schem = 'PUBLIC'"+ "and table_name = 'PAGES';");
    Ini.rs.next();
    if (Ini.rs.getInt("qwe") == 0) {
      Ini.stmt.executeUpdate("CREATE SEQUENCE SEQU");
      Ini.stmt.executeUpdate("CREATE CACHED TABLE PAGES (id bigint " + "GENERATED BY DEFAULT AS SEQUENCE SEQU PRIMARY KEY, " + "url varchar(7777), lastUpdateDate varchar(7777)) ");
      Ini.stmt.executeUpdate("CREATE CACHED TABLE LINKDATA (id int, " + "nazvanie varchar(777), linkURL varchar(777), razmer varchar(777)) ");
      Ini.stmt.executeUpdate("CREATE INDEX linkDataID ON LINKDATA (id)");
      Ini.stmt.executeUpdate("CREATE INDEX pagesURL ON PAGES (url)");
    }
  }
 catch (  Exception ex) {
    Ini.logger.fatal("Error on DB init",ex);
  }
}
 

Example 55

From project ipdburt, under directory /iddb-cli/src/main/java/iddb/cli/.

Source file: ConnectionFactory.java

  15 
vote

public static Connection getConnection() throws IOException, SQLException {
  if (instance == null) {
    instance=new ConnectionFactory();
  }
  return DriverManager.getConnection(instance.props.getProperty("url"),instance.props.getProperty("username"),instance.props.getProperty("password"));
}
 

Example 56

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/mk/simple/.

Source file: NodeMapInDb.java

  15 
vote

NodeMapInDb(String dir){
  try {
    String path=new File(dir,"nodes").getAbsolutePath();
    url="jdbc:h2:" + path + System.getProperty("mk.db","");
    Class.forName("org.h2.Driver");
    conn=DriverManager.getConnection(url);
    Statement stat=conn.createStatement();
    stat.execute("create table if not exists nodes(id bigint primary key, data varchar)");
    stat.execute("create table if not exists roots(key bigint primary key, value bigint) as select 0, 0");
    ResultSet rs=stat.executeQuery("select max(id) from nodes");
    rs.next();
    nextId=rs.getLong(1) + 1;
    rs=stat.executeQuery("select max(value) from roots");
    rs.next();
    long x=rs.getLong(1);
    if (x != 0) {
      root.setId(NodeId.get(x));
    }
    select=conn.prepareStatement("select * from nodes where id = ?");
    insert=conn.prepareStatement("insert into nodes sorted select ?, ?");
    merge=conn.prepareStatement("update roots set value = ?");
  }
 catch (  Exception e) {
    throw ExceptionFactory.convert(e);
  }
}
 

Example 57

From project JavaChat, under directory /ChatServer/src/Core/.

Source file: Database.java

  15 
vote

public Database(String connString) throws Exception {
  System.out.printf("\nInitializing database connection.\n");
  System.out.printf("Connection String: %s\n",connString);
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  conn=DriverManager.getConnection(connString);
  System.out.printf("Database Connection Successful\n");
}
 

Example 58

From project JavaMUD, under directory /src/com/mud/datalayer/.

Source file: DatabaseTesting.java

  15 
vote

public static void main(){
  Connection con=null;
  PreparedStatement st=null;
  ResultSet rs=null;
  String dbName="MudTest";
  String url="jdbc:mysql://localhost:3306/" + dbName;
  String user="root";
  String password="root";
  try {
    con=DriverManager.getConnection(url,user,password);
    st=con.prepareStatement("INSERT INTO Testing(Id) VALUES(?)");
    for (int i=1; i <= 1000; i++) {
      st.setInt(1,i * 2);
      st.executeUpdate();
    }
  }
 catch (  SQLException ex) {
    Logger lgr=Logger.getLogger(DatabaseTesting.class.getName());
    lgr.log(Level.SEVERE,ex.getMessage(),ex);
  }
 finally {
    try {
      if (st != null) {
        st.close();
      }
      if (con != null) {
        con.close();
      }
    }
 catch (    SQLException ex) {
      Logger lgr=Logger.getLogger(DatabaseTesting.class.getName());
      lgr.log(Level.SEVERE,ex.getMessage(),ex);
    }
  }
}
 

Example 59

From project JavaStory, under directory /Core/src/main/java/javastory/db/.

Source file: Database.java

  15 
vote

private Database(){
  try {
    DriverManager.registerDriver(new Driver());
  }
 catch (  final SQLException ex) {
    Logger.getLogger(Database.class.getName()).log(Level.SEVERE,null,ex);
  }
  this.connections=new ConcurrentLinkedQueue<>();
  final Map<String,String> properties=this.loadDbProperties();
  this.url=properties.get("url");
  this.username=properties.get("username");
  this.password=properties.get("password");
}
 

Example 60

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/mediation/task/.

Source file: SaveToJDBCMediationErrorHandler.java

  15 
vote

protected Connection getConnection() throws SQLException, ClassNotFoundException, TaskException {
  String driver=getParameter(PARAM_DRIVER.getName(),DRIVER_DEFAULT);
  Object url=parameters.get(PARAM_DATABASE_URL.getName());
  if (url == null) {
    throw new TaskException("Error, expected mandatory parameter databae_url");
  }
  String username=getParameter(PARAM_DATABASE_USERNAME.getName(),DATABASE_USERNAME_DEFAULT);
  String password=getParameter(PARAM_DATABASE_PASSWORD.getName(),DATABASE_PASSWORD_DEFAULT);
  Class.forName(driver);
  return DriverManager.getConnection((String)url,username,password);
}
 

Example 61

From project jboss-jpa, under directory /impl/src/test/java/org/jboss/jpa/impl/test/beanvalidation/.

Source file: MinimalBeanValidationTestCase.java

  15 
vote

@BeforeClass public static void beforeClass() throws Exception {
  driver=new jdbcDriver();
  DriverManager.registerDriver(driver);
  namingServer=new SingletonNamingServer();
  JNDIManager.bindJTAImplementation();
  transactionManager=(TransactionManager)new InitialContext().lookup("java:/TransactionManager");
}
 

Example 62

From project jdbi, under directory /src/main/java/org/skife/jdbi/v2/.

Source file: DBI.java

  15 
vote

/** 
 * Create a DBI which directly uses the DriverManager
 * @param url JDBC URL for connections
 */
public DBI(final String url){
  this(new ConnectionFactory(){
    public Connection openConnection() throws SQLException {
      return DriverManager.getConnection(url);
    }
  }
);
}
 

Example 63

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/dao/ds/.

Source file: SimpleDSDAOFactory.java

  15 
vote

/** 
 * Creates a new instance of SimpleDataSource.
 * @param driver the jdbc driver.
 * @param url the url for connecting to the data source.
 * @param username the username used in connection.
 * @param password the password used in connection.
 * @throws ClassNotFoundException if the driver class was not found.
 * @throws SQLException if the url is invalid or a database access erroroccurs.
 */
public SimpleDataSource(String driver,String url,String username,String password) throws ClassNotFoundException, SQLException {
  Class.forName(driver);
  DriverManager.getDriver(url);
  this.url=url;
  this.username=username;
  this.password=password;
}
 

Example 64

From project jforum2, under directory /src/net/jforum/.

Source file: SimpleConnection.java

  15 
vote

/** 
 * @see net.jforum.Connection#getConnection()
 */
public Connection getConnection(){
  try {
    return DriverManager.getConnection(SystemGlobals.getValue(ConfigKeys.DATABASE_CONNECTION_STRING));
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new DatabaseException(e);
  }
}
 

Example 65

From project Jobs, under directory /src/main/java/me/zford/jobs/dao/.

Source file: JobsConnectionPool.java

  15 
vote

public JobsConnectionPool(Jobs core,String driverName,String url,String username,String password) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
  Driver driver=(Driver)Class.forName(driverName,true,core.getJobsClassloader()).newInstance();
  JobsDriver jDriver=new JobsDriver(driver);
  DriverManager.registerDriver(jDriver);
  this.url=url;
  this.username=username;
  this.password=password;
}
 

Example 66

From project jPOS, under directory /compat_1_5_2/src/main/java/org/jpos/tpl/.

Source file: ConnectionPool.java

  15 
vote

private Connection makeNewConnection() throws SQLException {
  try {
    Class.forName(driver);
    Connection connection=DriverManager.getConnection(url,username,password);
    return (connection);
  }
 catch (  ClassNotFoundException cnfe) {
    throw new SQLException("Can't find class for driver: " + driver);
  }
}
 

Example 67

From project jspwiki, under directory /tests/org/apache/wiki/.

Source file: HsqlDbUtils.java

  15 
vote

/** 
 * Obtains a  {@link Connection}.
 * @return the obtained {@link Connection}.
 * @throws IOException problems occurred loading jdbc properties file.
 * @throws SQLException problems occurred obtaining the {@link Connection}.
 */
Connection getConnection() throws IOException, SQLException {
  Connection conn;
  Properties jProps=loadPropertiesFrom("tests/etc/db/jdbc.properties");
  conn=DriverManager.getConnection(jProps.getProperty("jdbc.driver.url"),jProps.getProperty("jdbc.admin.id"),jProps.getProperty("jdbc.admin.password"));
  return conn;
}
 

Example 68

From project junit-rules, under directory /src/main/java/junit/rules/derby/.

Source file: DerbyDataSourceRule.java

  15 
vote

/** 
 * Setup Derby
 * @throws Throwable if setup fails
 */
@Override protected final void setUp() throws Throwable {
  logger.debug("setUp()");
  final String jdbcUrl=constructJdbcUrl();
  logger.debug("Using JDBC URL: " + jdbcUrl);
  DriverManager.getConnection(jdbcUrl);
  final DriverManagerDataSource ds=new DriverManagerDataSource();
  ds.setJdbcUrl(jdbcUrl);
  dataSource=ds;
  logger.info("Initialized Derby database at \"" + jdbcUrl + "\"");
}
 

Example 69

From project karaf, under directory /main/src/test/java/org/apache/karaf/main/lock/.

Source file: BaseJDBCLockIntegrationTest.java

  15 
vote

Connection getConnection(String url,String user,String password) throws ClassNotFoundException, SQLException {
  Class.forName(driver);
  Connection connection=DriverManager.getConnection(url,user,password);
  connection.setAutoCommit(false);
  return connection;
}
 

Example 70

From project KarateGeek, under directory /KarateGeek/src/us/elfua/karategeek/dataManagement/.

Source file: DataBaseConnection.java

  15 
vote

private Connection connect(){
  System.out.println("-------- PostgreSQL " + "JDBC Connection Testing ------------");
  try {
    Class.forName("org.postgresql.Driver");
  }
 catch (  ClassNotFoundException e) {
    System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
    e.printStackTrace();
  }
  System.out.println("PostgreSQL JDBC Driver Registered!");
  try {
    this.connection=DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/testdb","mkyong","123456");
  }
 catch (  SQLException e) {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
  }
  if (connection != null) {
    System.out.println("You made it, take control your database now!");
  }
 else {
    System.out.println("Failed to make connection!");
  }
  return this.connection;
}
 

Example 71

From project kevoree-library, under directory /javase/org.kevoree.library.javase.derby/src/main/java/org/kevoree/library/derby/.

Source file: DerbySampleComponent.java

  15 
vote

@Start public void start(){
  Bundle bundle=(Bundle)this.getDictionary().get("osgi.bundle");
  try {
    bundle.loadClass(driver).newInstance();
    Connection conn=DriverManager.getConnection("jdbc:derby:" + this.getName() + ";create=true",new Properties());
    logger.debug("derby started !");
  }
 catch (  Exception e) {
    logger.error("Fail to start " + this.getName(),e);
  }
}
 

Example 72

From project kwegg, under directory /NewsCommon/src/com/kwegg/common/db/.

Source file: SimpleTableHandler.java

  15 
vote

public SimpleTableHandler(){
  try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn=DriverManager.getConnection(url,userName,password);
    System.out.println("Database connection established");
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
catch (  SQLException e) {
    System.out.println("test");
    e.printStackTrace();
  }
}
 

Example 73

From project l2jserver2, under directory /l2jserver2-tools/src/main/java/com/l2jserver/model/template/character/.

Source file: CharacterTemplateConverter.java

  15 
vote

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
  Class.forName("com.mysql.jdbc.Driver");
  final File target=new File("generated/template");
  System.out.println("Generating template classes...");
  final JAXBContext c=JAXBContext.newInstance(CharacterTemplate.class);
  c.generateSchema(new SchemaOutputResolver(){
    @Override public Result createOutput(    String namespaceUri,    String suggestedFileName) throws IOException {
      return new StreamResult(new File(target,"character.xsd"));
    }
  }
);
  final Marshaller m=c.createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  final Connection conn=DriverManager.getConnection(JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD);
  try {
    final PreparedStatement st=conn.prepareStatement("SELECT * FROM char_templates " + "LEFT JOIN lvlupgain ON (char_templates.Classid = lvlupgain.classid)");
    try {
      st.execute();
      final ResultSet rs=st.getResultSet();
      while (rs.next()) {
        CharacterTemplate t=fillTemplate(rs);
        final File file=new File(target,"character/" + camelCase(t.getID().getCharacterClass().name()) + ".xml");
        file.getParentFile().mkdirs();
        m.marshal(t,file);
      }
    }
  finally {
      st.close();
    }
  }
  finally {
    conn.close();
  }
}
 

Example 74

From project log4j, under directory /src/main/java/org/apache/log4j/jdbc/.

Source file: JDBCAppender.java

  15 
vote

/** 
 * Override this to link with your connection pooling system. By default this creates a single connection which is held open until the object is garbage collected.
 */
protected Connection getConnection() throws SQLException {
  if (!DriverManager.getDrivers().hasMoreElements())   setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
  if (connection == null) {
    connection=DriverManager.getConnection(databaseURL,databaseUser,databasePassword);
  }
  return connection;
}
 

Example 75

From project log4jna, under directory /thirdparty/log4j/src/main/java/org/apache/log4j/jdbc/.

Source file: JDBCAppender.java

  15 
vote

/** 
 * Override this to link with your connection pooling system. By default this creates a single connection which is held open until the object is garbage collected.
 */
protected Connection getConnection() throws SQLException {
  if (!DriverManager.getDrivers().hasMoreElements())   setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
  if (connection == null) {
    connection=DriverManager.getConnection(databaseURL,databaseUser,databasePassword);
  }
  return connection;
}
 

Example 76

From project logback, under directory /logback-core/src/main/java/ch/qos/logback/core/db/.

Source file: DriverManagerConnectionSource.java

  15 
vote

/** 
 * @see ch.qos.logback.core.db.ConnectionSource#getConnection()
 */
public Connection getConnection() throws SQLException {
  if (getUser() == null) {
    return DriverManager.getConnection(url);
  }
 else {
    return DriverManager.getConnection(url,getUser(),getPassword());
  }
}
 

Example 77

From project lor-jamwiki, under directory /jamwiki-core/src/main/java/org/jamwiki/db/.

Source file: DatabaseConnection.java

  15 
vote

/** 
 * Return a connection to the database with the specified parameters. The caller <b>must</b> close this connection when finished!
 * @param driver A String indicating the full path for the database driver class.
 * @param url The JDBC driver URL.
 * @param user The database user.
 * @param password The database user password.
 * @throws SQLException Thrown if any failure occurs while getting the test connection.
 */
protected static Connection getTestConnection(String driver,String url,String user,String password) throws SQLException {
  if (url.startsWith("jdbc:")) {
    if (!StringUtils.isBlank(driver)) {
      try {
        Utilities.forName(driver);
      }
 catch (      ClassNotFoundException e) {
        throw new SQLException("Unable to instantiate class with name: " + driver);
      }
    }
    return DriverManager.getConnection(url,user,password);
  }
 else {
    DataSource testDataSource=null;
    try {
      Context ctx=new InitialContext();
      testDataSource=(DataSource)ctx.lookup(url);
    }
 catch (    NamingException e) {
      logger.error("Failure while configuring JNDI data source with URL: " + url,e);
      throw new SQLException("Unable to configure JNDI data source with URL " + url + ": "+ e.toString());
    }
    return testDataSource.getConnection();
  }
}
 

Example 78

From project mapsforge-map-writer, under directory /src/main/java/org/mapsforge/storage/tile/.

Source file: PCTilePersistenceManager.java

  15 
vote

private void openOrCreateDB() throws ClassNotFoundException, SQLException {
  Class.forName("org.sqlite.JDBC");
  this.conn=DriverManager.getConnection("jdbc:sqlite:/" + this.path);
  this.conn.setAutoCommit(false);
  this.stmt=this.conn.createStatement();
  File dbFile=new File(this.path);
  if (dbFile.length() == 0) {
    createDatabase();
    initializePrivateStatements();
  }
 else {
    initializePrivateStatements();
    readMetaDataFromDB();
  }
  initializePrivateStatements();
}
 

Example 79

From project marabou, under directory /src/main/java/net/launchpad/marabou/db/.

Source file: HSQLDBClient.java

  15 
vote

protected HSQLDBClient(){
  try {
    conn=DriverManager.getConnection("jdbc:hsqldb:mem:maraboudb","SA","");
    update("CREATE TABLE marabou (id INTEGER IDENTITY, file VARCHAR(256) UNIQUE, artist VARCHAR(256), " + "title VARCHAR(256), album VARCHAR(256), track VARCHAR(256), year VARCHAR(256), genre VARCHAR(256)," + "comments VARCHAR(256), disc_number VARCHAR(256), composer VARCHAR(256),"+ "length VARCHAR(28), bitrate VARCHAR(256), samplerate VARCHAR(256), channels VARCHAR(28),"+ "encoding VARCHAR(256))");
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
}
 

Example 80

From project MCbb, under directory /de/javakara/manf/database/.

Source file: MySQLManager.java

  15 
vote

public MySQLManager(String host,String port,String db,String user,String pw) throws SQLException, ClassNotFoundException {
  Class.forName("com.mysql.jdbc.Driver");
  url="jdbc:mysql://" + host + ":"+ port+ "/"+ db;
  Connection con=DriverManager.getConnection(url,user,pw);
  stmt=con.createStatement();
}
 

Example 81

From project MEditor, under directory /editor-confutils/src/main/java/cz/mzk/editor/server/DAO/.

Source file: AbstractDAO.java

  15 
vote

private void initConnectionWithoutPool() throws DatabaseException {
  try {
    Class.forName(DRIVER);
  }
 catch (  ClassNotFoundException ex) {
    LOGGER.error("Could not find the driver " + DRIVER,ex);
  }
  String login=conf.getDBLogin();
  String password=conf.getDBPassword();
  String host=conf.getDBHost();
  String port=conf.getDBPort();
  String name=conf.getDBName();
  if (!contextIsCorrect && !conf.isLocalhost() && pool == null && login != null && password != null && port != null && name != null) {
    createCorrectContext(login,password,port,name);
  }
  if (password == null || password.length() < 3) {
    LOGGER.error("Unable to connect to database at 'jdbc:postgresql://" + host + ":"+ port+ "/"+ name+ "' reason: no password set.");
    return;
  }
  try {
    conn=DriverManager.getConnection("jdbc:postgresql://" + host + ":"+ port+ "/"+ name,login,password);
  }
 catch (  SQLException ex) {
    LOGGER.error("Unable to connect to database at 'jdbc:postgresql://" + host + ":"+ port+ "/"+ name+ "'",ex);
    throw new DatabaseException("Unable to connect to database.");
  }
}
 

Example 82

From project medsavant, under directory /MedSavantServerEngine/src/org/ut/biolab/medsavant/db/connection/.

Source file: ConnectionController.java

  15 
vote

public static Connection connectOnce(String host,int port,String db,String user,String pass) throws SQLException {
  try {
    Class.forName(DRIVER).newInstance();
  }
 catch (  Exception ex) {
    if (ex instanceof ClassNotFoundException || ex instanceof InstantiationException) {
      throw new SQLException("Unable to load MySQL driver.");
    }
  }
  return DriverManager.getConnection(getConnectionString(host,port,db),user,pass);
}
 

Example 83

From project Metamorphosis, under directory /metamorphosis-tools/src/main/java/com/taobao/metamorphosis/tools/query/.

Source file: Query.java

  15 
vote

private void initMysqlClient(final String jdbcConf) throws InitException {
  try {
    final Properties jdbcProperties=ResourceUtils.getResourceAsProperties(jdbcConf);
    final String url=jdbcProperties.getProperty("jdbc.url");
    final String userName=jdbcProperties.getProperty("jdbc.username");
    final String userPassword=jdbcProperties.getProperty("jdbc.password");
    final String jdbcUrl=url + "&user=" + userName+ "&password="+ userPassword;
    System.out.println("mysql connect parameter is :\njdbc.url=" + jdbcUrl);
    Class.forName("com.mysql.jdbc.Driver");
    this.connect=DriverManager.getConnection(jdbcUrl);
  }
 catch (  final FileNotFoundException e) {
    throw new InitException(e.getMessage(),e.getCause());
  }
catch (  final Exception e) {
    throw new InitException("mysql connect init failed. " + e.getMessage(),e.getCause());
  }
}
 

Example 84

From project MineStarLibrary, under directory /src/main/java/de/minestar/minestarlibrary/database/.

Source file: DatabaseConnection.java

  15 
vote

/** 
 * Help method to create a connection to a MySQL database.
 * @param host Hosting the MySQL Database
 * @param port Port for MySQL Client
 * @param database Name of the database
 * @param userName User with enough permission to access the database
 * @param password Password for the user. It will deleted by this
 */
private void createMySQLConnection(String host,String port,String database,String userName,String password){
  try {
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://" + host + ":"+ port+ "/"+ database+ "?autoReconnect=true",userName,password);
  }
 catch (  Exception e) {
    ConsoleUtils.printException(e,pluginName,"Can't create a MySQL connection! Please check your connection information in the sql.config and your database connection!");
  }
  userName=null;
  password=null;
  System.gc();
}
 

Example 85

From project miso-lims, under directory /sqlstore/src/test/java/uk/ac/bbsrc/tgac/miso/sqlstore/.

Source file: LimsDAOTestCase.java

  15 
vote

@Override protected IDataSet getDataSet() throws Exception {
  if (dataSet == null) {
    System.out.print("Getting dataset...");
    InputStream in=LimsDAOTestCase.class.getClassLoader().getResourceAsStream("test.db.properties");
    Properties props=new Properties();
    props.load(in);
    System.out.print("properties loaded...");
    Connection jdbcConnection=DriverManager.getConnection(props.getProperty("db.url"),props.getProperty("db.username"),props.getProperty("db.password"));
    IDatabaseConnection connection=new DatabaseConnection(jdbcConnection);
    DatabaseConfig config=connection.getConfig();
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,new MySqlDataTypeFactory());
    System.out.print("mysql connection set...");
    dataSet=new QueryDataSet(connection);
    for (    String table : tables) {
      dataSet.addTable(table);
    }
    System.out.print("dataset ready.\n");
  }
  return dataSet;
}
 

Example 86

From project mmoCore, under directory /src/main/java/mmo/Core/SQLibrary/.

Source file: HSQLDB.java

  15 
vote

@Override public Connection open(){
  if (!connected && initialize()) {
    String url="";
    try {
      url="jdbc:hsqldb:hsql://" + this.hostname + ":"+ this.port+ "/"+ this.database;
      connection=DriverManager.getConnection(url,this.username,this.password);
    }
 catch (    SQLException e) {
      this.writeError(url,true);
      this.writeError("Could not be resolved because of an SQL Exception: " + e.getMessage() + ".",true);
    }
    connected=connection == null;
  }
  return connection;
}
 

Example 87

From project mobilis, under directory /MobilisXHunt/MobilisXHunt_DBImporter/src/de/tudresden/inf/rn/mobilis/android/xhunt/dbimporter/.

Source file: SqlHelper.java

  15 
vote

/** 
 * Check db structure.
 * @return true, if successful
 */
public boolean checkDbStructure(){
  boolean isStructureOk=false;
  try {
    mMysqlConnection=DriverManager.getConnection(getConnectionURI());
    mPreparedStatement=mMysqlConnection.prepareStatement("select ID, Name, Description, Version from " + mDbName + "."+ TABLE_AREA);
    mPreparedStatement.executeQuery();
    mPreparedStatement=mMysqlConnection.prepareStatement("select Area_ID, Route_ID from " + mDbName + "."+ TABLE_AREA_HAS_ROUTES);
    mPreparedStatement.executeQuery();
    mPreparedStatement=mMysqlConnection.prepareStatement("select ID, Ticket_ID, Name, StartName, EndName from " + mDbName + "."+ TABLE_ROUTE);
    mPreparedStatement.executeQuery();
    mPreparedStatement=mMysqlConnection.prepareStatement("select Route_ID, Station_ID, Position from " + mDbName + "."+ TABLE_ROUTE_HAS_STATIONS);
    mPreparedStatement.executeQuery();
    mPreparedStatement=mMysqlConnection.prepareStatement("select ID, Name, Abbreviation, Latitude, Longitude from " + mDbName + "."+ TABLE_STATION);
    mPreparedStatement.executeQuery();
    mPreparedStatement=mMysqlConnection.prepareStatement("select ID, Name, Icon, Is_Superior from " + mDbName + "."+ TABLE_TICKET);
    mPreparedStatement.executeQuery();
    isStructureOk=true;
  }
 catch (  SQLException e) {
    e.printStackTrace();
    isStructureOk=false;
  }
  return isStructureOk;
}
 

Example 88

From project ndg, under directory /ndg-server-core/src/main/java/br/org/indt/ndg/server/client/.

Source file: TemporaryOpenRosaBussinessDelegate.java

  15 
vote

private Connection getDbConnection() throws SQLException {
  String url="jdbc:mysql://localhost:3306/ndg";
  String dbUser="ndg";
  String dbPwd="ndg";
  return DriverManager.getConnection(url,dbUser,dbPwd);
}
 

Example 89

From project neo4j-jdbc, under directory /src/test/java/org/neo4j/jdbc/.

Source file: DriverTest.java

  15 
vote

@Test public void testDriverRegistration(){
  try {
    java.sql.Driver driver=DriverManager.getDriver(jdbcUrl());
    Assert.assertNotNull(driver);
    Assert.assertEquals(this.driver.getClass(),driver.getClass());
  }
 catch (  SQLException e) {
    Assert.fail(e.getLocalizedMessage());
  }
}
 

Example 90

From project nevernote, under directory /src/cx/fbn/nevernote/.

Source file: NeverNote.java

  15 
vote

private static boolean databaseCheck(String url,String userid,String userPassword,String cypherPassword){
  Connection connection;
  try {
    Class.forName("org.h2.Driver");
  }
 catch (  ClassNotFoundException e1) {
    e1.printStackTrace();
    System.exit(16);
  }
  try {
    String passwordString=null;
    if (cypherPassword == null || cypherPassword.trim().equals(""))     passwordString=userPassword;
 else     passwordString=cypherPassword + " " + userPassword;
    connection=DriverManager.getConnection(url,userid,passwordString);
  }
 catch (  SQLException e) {
    return false;
  }
  try {
    connection.close();
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
  return true;
}
 

Example 91

From project Newsreader, under directory /bundles/org.eclipse.ecf.protocol.nntp.store.derby/src/org/eclipse/ecf/protocol/nntp/store/derby/internal/.

Source file: Database.java

  15 
vote

public static Database createDatabase(String root,boolean initialize) throws StoreException {
  System.setProperty("derby.system.home",root);
  String connectionURL="jdbc:derby:Salvo;create=true";
  try {
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    Connection connection=DriverManager.getConnection(connectionURL,"salvo","salvo");
    return new Database(connection,initialize);
  }
 catch (  Exception e) {
    throw new StoreException("Problem creating store",e);
  }
}
 

Example 92

From project niravCS2103, under directory /CS2103/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/jdbc/.

Source file: JDBCAppender.java

  15 
vote

/** 
 * Override this to link with your connection pooling system. By default this creates a single connection which is held open until the object is garbage collected.
 */
protected Connection getConnection() throws SQLException {
  if (!DriverManager.getDrivers().hasMoreElements())   setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
  if (connection == null) {
    connection=DriverManager.getConnection(databaseURL,databaseUser,databasePassword);
  }
  return connection;
}
 

Example 93

From project nuxeo-services, under directory /nuxeo-platform-directory/nuxeo-platform-directory-sql/src/main/java/org/nuxeo/ecm/directory/sql/.

Source file: SimpleDataSource.java

  15 
vote

@Override public Connection getConnection() throws SQLException {
  Connection con=null;
  int tryNo=0;
  for (; ; ) {
    try {
      con=DriverManager.getConnection(url,user,password);
      break;
    }
 catch (    SQLException e) {
      if (++tryNo >= MAX_CONNECTION_TRIES) {
        throw e;
      }
      if (e.getErrorCode() != 12519) {
        throw e;
      }
      log.warn(String.format("Connections open too fast, retrying in %ds: %s",tryNo,e.getMessage().replace("\n"," ")));
      try {
        Thread.sleep(1000 * tryNo);
      }
 catch (      InterruptedException ie) {
        Thread.currentThread().interrupt();
      }
    }
  }
  con.setAutoCommit(false);
  return con;
}
 

Example 94

From project odata4j, under directory /odata4j-core/src/main/java/org/odata4j/producer/jdbc/.

Source file: Jdbc.java

  15 
vote

public <T>T execute(ThrowingFunc1<Connection,T> execute){
  try {
    Class.forName(driverClassname);
  }
 catch (  ClassNotFoundException e) {
    throw Throwables.propagate(e);
  }
  Connection conn=null;
  try {
    conn=DriverManager.getConnection(url,user,password);
    return execute.apply(conn);
  }
 catch (  Exception e) {
    throw Throwables.propagate(e);
  }
 finally {
    if (conn != null) {
      try {
        conn.close();
      }
 catch (      SQLException e) {
        throw Throwables.propagate(e);
      }
    }
  }
}
 

Example 95

From project OpenEMRConnect, under directory /adt_companion/src/ke/go/moh/oec/adt/controller/.

Source file: ResourceManager.java

  15 
vote

private static Connection createDatabaseConnection(String name) throws SQLException {
  Connection connection=null;
  if (name.equals("source")) {
    connection=DriverManager.getConnection(Mediator.getProperty("source.url"),Mediator.getProperty("source.username"),Mediator.getProperty("source.password"));
  }
 else   if (name.equals("shadow")) {
    connection=DriverManager.getConnection(Mediator.getProperty("shadow.url"),Mediator.getProperty("shadow.username"),Mediator.getProperty("shadow.password"));
  }
  return connection;
}
 

Example 96

From project OpenSettlers, under directory /src/java/soc/server/database/.

Source file: SOCDBHelper.java

  15 
vote

/** 
 * initialize and checkConnection use this to get ready.
 */
private static boolean connect() throws SQLException {
  connection=DriverManager.getConnection(dbURL,userName,password);
  errorCondition=false;
  createAccountCommand=connection.prepareStatement(CREATE_ACCOUNT_COMMAND);
  recordLoginCommand=connection.prepareStatement(RECORD_LOGIN_COMMAND);
  userPasswordQuery=connection.prepareStatement(USER_PASSWORD_QUERY);
  hostQuery=connection.prepareStatement(HOST_QUERY);
  lastloginUpdate=connection.prepareStatement(LASTLOGIN_UPDATE);
  saveGameCommand=connection.prepareStatement(SAVE_GAME_COMMAND);
  robotParamsQuery=connection.prepareStatement(ROBOT_PARAMS_QUERY);
  resetHumanStats=connection.prepareStatement(RESET_HUMAN_STATS);
  userFaceQuery=connection.prepareStatement(USER_FACE_QUERY);
  userFaceUpdate=connection.prepareStatement(USER_FACE_UPDATE);
  updateRobotStats=connection.prepareStatement(UPDATE_ROBOT_STATS);
  updateUserStats=connection.prepareStatement(UPDATE_USER_STATS);
  return true;
}
 

Example 97

From project org.openscada.atlantis, under directory /org.openscada.da.server.jdbc/src/org/openscada/da/server/jdbc/.

Source file: Connection.java

  15 
vote

protected java.sql.Connection createConnection() throws SQLException {
  if (this.timeout != null) {
    DriverManager.setLoginTimeout(this.timeout / 1000);
  }
  final java.sql.Connection connection=DriverManager.getConnection(this.uri,this.username,this.password);
  return connection;
}
 

Example 98

From project osiris, under directory /src/osiris/data/sql/.

Source file: SqlConnection.java

  15 
vote

/** 
 * Connect.
 */
public void connect(){
  String tag="[SQL" + (Settings.SQLITE_SAVING ? "ite" : "") + "]";
  try {
    if (Main.isLocal()) {
      System.out.println(tag + " Connecting to Database (" + database+ ")... ");
    }
    if (!Settings.SQLITE_SAVING) {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      String url="jdbc:mysql://" + host + "/"+ database;
      connection=DriverManager.getConnection(url,username,password);
    }
 else {
      Class.forName("org.sqlite.JDBC");
      connection=DriverManager.getConnection("jdbc:sqlite:./data/database/osirisdb.sqlite");
    }
    if (Main.isLocal()) {
      System.out.println(tag + " SUCCESS!");
    }
  }
 catch (  Exception e) {
    System.err.println(tag + " FAILURE: " + e);
  }
}