List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:com.glaf.core.jdbc.DBConnectionFactory.java
public static Connection getConnection(java.util.Properties props) { Connection connection = null; try {/* w w w.j a va 2s . c om*/ if (props != null) { if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE)); connection = ds.getConnection(); } else { String systemName = props.getProperty(DBConfiguration.JDBC_NAME); if (StringUtils.isNotEmpty(systemName)) { ConnectionProvider provider = ConnectionProviderFactory.createProvider(systemName); if (provider != null) { connection = provider.getConnection(); } } else { ConnectionProvider provider = ConnectionProviderFactory.createProvider(props); if (provider != null) { connection = provider.getConnection(); } } } } if (connection != null) { ConnectionThreadHolder.addConnection(connection); } return connection; } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:com.glaf.core.jdbc.DBConnectionFactory.java
public static Connection getConnection(String systemName) { if (systemName == null) { throw new RuntimeException("systemName is required."); }/*from w ww . j av a 2 s . co m*/ logger.debug("systemName:" + systemName); Connection connection = null; try { Properties props = DBConfiguration.getDataSourcePropertiesByName(systemName); if (props != null) { if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE)); connection = ds.getConnection(); } else { ConnectionProvider provider = ConnectionProviderFactory.createProvider(systemName); if (provider != null) { connection = provider.getConnection(); } } } else { // DataSource ds = ContextFactory.getBean("dataSource"); // connection = ds.getConnection(); } if (connection != null) { ConnectionThreadHolder.addConnection(connection); } return connection; } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:com.glaf.core.jdbc.DBConnectionFactory.java
public static boolean checkConnection(String systemName) { if (systemName == null) { throw new RuntimeException("systemName is required."); }//from ww w. j a va2s .c o m logger.debug("systemName:" + systemName); Connection connection = null; try { Properties props = DBConfiguration.getDataSourcePropertiesByName(systemName); logger.debug("props:" + props); if (props != null) { if (StringUtils.isNotEmpty(props.getProperty(DBConfiguration.JDBC_DATASOURCE))) { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(props.getProperty(DBConfiguration.JDBC_DATASOURCE)); connection = ds.getConnection(); } else { ConnectionProvider provider = ConnectionProviderFactory.createProvider(systemName); if (provider != null) { connection = provider.getConnection(); } } } else { // DataSource ds = ContextFactory.getBean("dataSource"); // connection = ds.getConnection(); } if (connection != null) { ConnectionThreadHolder.addConnection(connection); } if (connection != null) { return true; } } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); } finally { JdbcUtils.close(connection); } return false; }
From source file:com.microsoft.sqlserver.jdbc.connection.PoolingTest.java
/** * setup connection, get connection from pool, and test threads * /*from w w w. j av a 2s. c o m*/ * @param ds * @throws SQLException */ private static void connect(DataSource ds) throws SQLException { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = ds.getConnection(); pst = con.prepareStatement("SELECT SUSER_SNAME()"); pst.setQueryTimeout(5); rs = pst.executeQuery(); // TODO : we are commenting this out due to AppVeyor failures. Will investigate later. // assertTrue(countTimeoutThreads() >= 1, "Timeout timer is missing."); while (rs.next()) { rs.getString(1); } } finally { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } }
From source file:org.dbmaintain.util.SQLTestUtils.java
/** * Executes the given update statement.//from w w w. j a v a 2 s . com * * @param sql The sql string for retrieving the items * @param dataSource The data source, not null * @return The nr of updates */ public static int executeUpdate(String sql, DataSource dataSource) { Connection connection = null; Statement statement = null; try { connection = dataSource.getConnection(); statement = connection.createStatement(); return statement.executeUpdate(sql); } catch (Exception e) { throw new DbMaintainException("Error while executing statement: " + sql, e); } finally { closeQuietly(connection, statement, null); } }
From source file:FacultyAdvisement.StudentRepository.java
public static void updateAllToNotAdvised(DataSource ds) throws SQLException { Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException("conn is null; Can't get db connection"); }//from w w w .j av a2 s . c o m try { PreparedStatement ps = conn.prepareStatement("update student set advised = \'false\'"); ps.execute(); } finally { conn.close(); } }
From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java
public static ArrayList<CommentaireOuvrages> getCommentaires(DataSource ds, int ouv_id) { ArrayList<CommentaireOuvrages> list = new ArrayList<CommentaireOuvrages>(); Connection con = null;//ww w .j a v a2s . c o m PreparedStatement stm; ResultSet rs; try { con = ds.getConnection(); stm = con.prepareStatement( "SELECT commentaireouvrages.id AS comid, commentaireouvrages.contenu_commentaire, commentaireouvrages.date_commentaire, utilisateur.id AS uid,utilisateur.pseudo, utilisateur.nom, utilisateur.prenom, utilisateur.type_user FROM commentaireouvrages INNER JOIN utilisateur ON commentaireouvrages.Utilisateurid=utilisateur.id WHERE commentaireouvrages.Ouvrageid=? ORDER BY commentaireouvrages.id DESC"); stm.setInt(1, ouv_id);//type user prof 1 rs = stm.executeQuery(); Utilisateur u = new Utilisateur(); CommentaireOuvrages co = new CommentaireOuvrages(); while (rs.next()) { co = new CommentaireOuvrages(); u = new Utilisateur(); u.setId(rs.getInt("uid")); u.setPseudo(rs.getString("pseudo")); u.setNom(rs.getString("nom")); u.setPrenom(rs.getString("prenom")); co.setId(rs.getInt("comid")); co.setContenu_commentaire(rs.getString("contenu_commentaire")); co.setDate_commentaire(rs.getString("date_commentaire")); co.setUtilisateur(u); list.add(co); } con.close(); rs.close(); } catch (SQLException ex) { Logger.getLogger(UtilisateurModele.class.getName()).log(Level.SEVERE, null, ex); } return list; }
From source file:com.jagornet.dhcp.db.DbSchemaManager.java
/** * Validate schema./*from w ww. j a va2s . c o m*/ * * @param dataSource the data source * * @throws SQLException if there is a problem with the database * @throws IOExcpetion if there is a problem reading the schema file * * returns true if database was created, false otherwise */ public static boolean validateSchema(DataSource dataSource, String schemaFilename, int schemaVersion) throws SQLException, IOException { boolean schemaCreated = false; List<String> tableNames = new ArrayList<String>(); Connection conn = dataSource.getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); log.info("JDBC Connection Info:\n" + "url = " + dbMetaData.getURL() + "\n" + "database = " + dbMetaData.getDatabaseProductName() + " " + dbMetaData.getDatabaseProductVersion() + "\n" + "driver = " + dbMetaData.getDriverName() + " " + dbMetaData.getDriverVersion()); String[] types = { "TABLE" }; ResultSet rs = dbMetaData.getTables(null, null, "%", types); if (rs.next()) { tableNames.add(rs.getString("TABLE_NAME")); } else { createSchema(dataSource, schemaFilename); dbMetaData = conn.getMetaData(); rs = dbMetaData.getTables(null, null, "%", types); schemaCreated = true; } while (rs.next()) { tableNames.add(rs.getString("TABLE_NAME")); } String[] schemaTableNames; if (schemaVersion <= 1) { schemaTableNames = TABLE_NAMES; } else { schemaTableNames = TABLE_NAMES_V2; } if (tableNames.size() == schemaTableNames.length) { for (int i = 0; i < schemaTableNames.length; i++) { if (!tableNames.contains(schemaTableNames[i])) { throw new IllegalStateException("Invalid database schema: unknown tables"); } } } else { throw new IllegalStateException("Invalid database schema: wrong number of tables"); } return schemaCreated; }
From source file:com.hangum.tadpole.engine.manager.TadpoleSQLTransactionManager.java
/** * java.sql.connection? ? ./*from ww w .j a v a 2 s . c om*/ * * @param userId * @param userDB * * @return * @throws Exception */ public static Connection getInstance(final String userId, final UserDBDAO userDB) throws Exception { if (logger.isDebugEnabled()) logger.debug("[userId]" + userId + "[userDB]" + userDB.getUrl() + " / " + userDB.getUsers()); synchronized (dbManager) { final String searchKey = getKey(userId, userDB); TransactionDAO transactionDAO = dbManager.get(searchKey); if (transactionDAO == null) { try { DataSource ds = DBCPConnectionManager.getInstance().getDataSource(userId, userDB); transactionDAO = new TransactionDAO(); Connection conn = ds.getConnection(); conn.setAutoCommit(false); transactionDAO.setConn(conn); transactionDAO.setUserId(userId); transactionDAO.setUserDB(userDB); transactionDAO.setStartTransaction(new Date(System.currentTimeMillis())); transactionDAO.setKey(searchKey); dbManager.put(searchKey, transactionDAO); if (logger.isDebugEnabled()) logger.debug("\t New connection SQLMapSession."); } catch (Exception e) { logger.error("transaction connection", e); } } else { if (logger.isDebugEnabled()) { logger.debug("\t Already register SQLMapSession."); logger.debug("\t Is auto commit " + transactionDAO.getConn().getAutoCommit()); } } if (logger.isDebugEnabled()) logger.debug("[conn code]" + transactionDAO.toString()); return transactionDAO.getConn(); } }
From source file:ips1ap101.lib.core.db.util.DB.java
public static Connection connect(String dataSourceName, boolean autoCommit) { Bitacora.trace(DB.class, "connect", dataSourceName, autoCommit); Connection connection = null; try {/*from w w w .j av a 2s . c om*/ DataSource dataSource = (DataSource) InitialContext.doLookup(dataSourceName); connection = dataSource.getConnection(); if (setAutoCommit(connection, autoCommit)) { Bitacora.stamp(connection, dataSourceName); return connection; } } catch (NamingException | SQLException ex) { Bitacora.logFatal(ex); } close(connection); return null; }