Java Code Examples for org.apache.commons.dbutils.DbUtils#close()

The following examples show how to use org.apache.commons.dbutils.DbUtils#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RmdbRepository.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Save row data.
 * 
 * @param insertSql
 * @throws Exception
 */
public void saveRowdata(String insertSql) throws Exception {
	Connection conn = null;
	try {
		QueryRunner runner = new QueryRunner();
		conn = dbFactory.getConnection();
		int num = runner.update(conn, insertSql);
		if (num <= 0) {
			log.warn("Failed save rowdata for sql: " + insertSql);
		}
	} catch (Exception e) {
		throw e;
	} finally {
		DbUtils.close(conn);
	}

}
 
Example 2
Source File: CleanService.java    From jforgame with Apache License 2.0 6 votes vote down vote up
private void clear(MergeServer server) {
        logger.error("开始对服务[{}]执行清档逻辑", server.getServerId());
        MergeConfig config = MergeConfig.getInstance();
        String sql = SqlFactory.createClearPlayerSql(config.getClear().getMinLevel(), config.getClear().getOfflineDays());
        logger.info("清档sql为 {}", sql);

        Connection targetConn = JdbcUtils.getConnection(server);
        int beforeCount = JdbcUtils.queryRecordSum(targetConn, "SELECT COUNT(1) FROM t_role;");
        logger.info("清档前[{}]服角色数量为{}", server.getServerId(), beforeCount);
//        JdbcUtils.execUpdate(targetConn, sql);
        int afterCount = JdbcUtils.queryRecordSum(targetConn, "SELECT COUNT(1) FROM t_role;");
        logger.info("清档前[{}]角色数量为{}", server.getServerId(), afterCount);
        List<String> clearTables = MergedTableRegistry.getInstance().listToDeleteTables();

        for (String table : clearTables) {
            logger.info("清空[{}]服【{}】表数据", server.getServerId(), table);
            String delSql = SqlFactory.createDeleteTableSql(table);
            JdbcUtils.execUpdate(targetConn, delSql);
        }
        try {
            DbUtils.close(targetConn);
        } catch (SQLException e) {
            logger.error("", e);
            throw new RuntimeException("");
        }
    }
 
Example 3
Source File: TableStructAnalyser.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
public TableStruct analyse(Connection connection, String table) throws SQLException {
    ResultSet structRs = null;
    ResultSet columnSet = null;
    TableStruct tableStruct = new TableStruct(table);
    try {
        structRs = connection.getMetaData().getPrimaryKeys(connection.getCatalog(), null, table);
        columnSet = connection.getMetaData().getColumns(null, "%", table, "%");
        while (structRs.next()) {
            tableStruct.getPrimaryKeys().add(structRs.getString("COLUMN_NAME"));
        }
        while (columnSet.next()) {
            tableStruct.getColumns().put(columnSet.getString("COLUMN_NAME"), columnSet.getString("TYPE_NAME"));
        }
    } catch (SQLException e) {
        try {
            DbUtils.close(structRs);
            DbUtils.close(columnSet);
        } catch (SQLException ignored) {
        }
        throw e;
    }
    return tableStruct;
}
 
Example 4
Source File: TxcSqlExecutorImpl.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
@Override
public void applyUndoLog(List<StatementInfo> statementInfoList) throws SQLException {
    Connection connection = null;
    try {
        connection = queryRunner.getDataSource().getConnection();
        connection.setAutoCommit(false);
        for (StatementInfo statementInfo : statementInfoList) {
            log.debug("txc > Apply undo log. sql: {}, params: {}", statementInfo.getSql(), statementInfo.getParams());
            queryRunner.update(connection, statementInfo.getSql(), statementInfo.getParams());
        }
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (connection != null) {
            connection.setAutoCommit(true);
            DbUtils.close(connection);
        }
    }
}
 
Example 5
Source File: MapListHandlerExample.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static void main(String[] args) throws SQLException {

		final String url = "jdbc:h2:./target/test;AUTO_SERVER=TRUE";
		final String driver = "org.h2.Driver";
		final String usr = "sa";
		final String pwd = "";

		QueryRunner run = new QueryRunner();

		DbUtils.loadDriver(driver);
		Connection conn = DriverManager.getConnection(url, usr, pwd);
		// -----------------------------------------------------------------------------------

		try {
			List<Map<String, Object>> maps = run.query(conn,
					"SELECT * FROM employee", new MapListHandler());
			System.out.println(maps);
		} finally {
			DbUtils.close(conn);
		}

	}
 
Example 6
Source File: BeanHandlerExample.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static void main(String[] args) throws SQLException {

		final String url = "jdbc:h2:./target/test;AUTO_SERVER=TRUE";
		final String driver = "org.h2.Driver";
		final String usr = "sa";
		final String pwd = "";

		QueryRunner run = new QueryRunner();

		DbUtils.loadDriver(driver);
		Connection conn = DriverManager.getConnection(url, usr, pwd);
		// -----------------------------------------------------------------------------------
		ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(
				Employee.class);

		try {
			Employee emp = run.query(conn,
					"SELECT * FROM employee WHERE employeename=?",
					resultHandler, "Jose");
			System.out.println(emp.getEmployeeId());
		} finally {
			DbUtils.close(conn);
		}

	}
 
Example 7
Source File: ArrayListHandlerExample.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static void main(String[] args) throws SQLException {

		final String url = "jdbc:h2:./target/test;AUTO_SERVER=TRUE";
		final String driver = "org.h2.Driver";
		final String usr = "sa";
		final String pwd = "";

		QueryRunner run = new QueryRunner();

		DbUtils.loadDriver(driver);
		Connection conn = DriverManager.getConnection(url, usr, pwd);
		// -----------------------------------------------------------------------------------

		try {
			List<Object[]> query = run.query(conn, "SELECT * FROM employee",
					new ArrayListHandler());
			for (Object[] objects : query) {
				System.out.println(Arrays.toString(objects));
			}
		} finally {
			DbUtils.close(conn);
		}

	}
 
Example 8
Source File: BeanListHandlerExample.java    From maven-framework-project with MIT License 6 votes vote down vote up
public static void main(String[] args) throws SQLException {

		final String url = "jdbc:h2:./target/test;AUTO_SERVER=TRUE";
		final String driver = "org.h2.Driver";
		final String usr = "sa";
		final String pwd = "";

		QueryRunner run = new QueryRunner();

		DbUtils.loadDriver(driver);

		Connection conn = DriverManager.getConnection(url, usr, pwd);
		// -----------------------------------------------------------------------------------
		ResultSetHandler<List<Employee>> resultListHandler = new BeanListHandler<Employee>(
				Employee.class);

		try {
			List<Employee> empList = run.query(conn, "SELECT * FROM employee",
					resultListHandler);
			System.out.println(empList);
		} finally {
			DbUtils.close(conn);
		}

	}
 
Example 9
Source File: TableStructAnalyser.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public TableStruct analyse(String table) throws SQLException {
    Connection connection = null;
    try {
        DTXLocalContext.makeUnProxy();
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        return analyse(connection, table);
    } finally {
        DTXLocalContext.undoProxyStatus();
        DbUtils.close(connection);
    }
}
 
Example 10
Source File: TableStructAnalyser.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public boolean existsTable(Connection connection, String table) throws SQLException {
    ResultSet resultSet = null;
    try {
        resultSet = connection.getMetaData().getTables(null, null, table, null);
        if (resultSet.next()) {
            return true;
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.close(resultSet);
    }
    return false;
}
 
Example 11
Source File: TableStructAnalyser.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
/**
 * 存在数据表判断
 *
 * @param tableName tableName
 * @return exists
 * @throws  SQLException SQLException
 */
public boolean existsTable(String tableName) throws SQLException {
    Connection connection = null;
    try {
        DTXLocalContext.makeUnProxy();
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        return existsTable(connection, tableName);
    } finally {
        DbUtils.close(connection);
        DTXLocalContext.undoProxyStatus();
    }
}
 
Example 12
Source File: TableCreator.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private void createTable() throws SQLException {
    String baseSql = createSql;
    if(constraints!=null){
        int lastParenthesis = baseSql.lastIndexOf(")");
        baseSql = baseSql.substring(0,lastParenthesis)+","+constraints+")";
    }
    String CREATE_SQL=tableName!=null?String.format(baseSql,tableName):baseSql;
    Statement statement = connection.createStatement();
    statement.setQueryTimeout(queryTimeout);
    try {
        statement.execute(CREATE_SQL);
    } finally {
        DbUtils.close(statement);
    }
}
 
Example 13
Source File: TableCreator.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private void createIndexes() throws SQLException {
    for (String indexSql : indexSqlList) {
        String INDEX_SQL = tableName == null ? indexSql : String.format(indexSql, tableName);
        Statement statement = connection.createStatement();
        statement.setQueryTimeout(queryTimeout);
        try {
            statement.execute(INDEX_SQL);
        } finally {
            DbUtils.close(statement);
        }
    }
}
 
Example 14
Source File: DBFacade.java    From DBus with Apache License 2.0 4 votes vote down vote up
/**
 * 保存新的version
 *
 * @param version
 * @return
 * @throws Exception
 */
public void createMetaVersion(MetaVersion version) throws Exception {
    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        String sql;

        sql = "insert into t_meta_version(db_name,schema_name,table_name,version,inner_version,schema_hash,update_time,ds_id,event_offset, event_pos,table_id,comments) values(?,?,?,?,?,?,?,?,?,?,?,?)";
        // 生成version信息
        ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        ps.setString(1, Utils.getDatasource().getDsName());
        ps.setString(2, version.getSchema());
        ps.setString(3, version.getTable());
        ps.setInt(4, version.getVersion());
        ps.setInt(5, version.getInnerVersion());
        ps.setObject(6, version.getSchemaHash());
        ps.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
        ps.setLong(8, Utils.getDatasource().getId());
        ps.setLong(9, version.getOffset());
        ps.setLong(10, version.getTrailPos());
        ps.setLong(11, version.getTableId());
        ps.setString(12, version.getComments());
        ps.executeUpdate();

        // 获取自动生成的ID
        ResultSet idSet = ps.getGeneratedKeys();
        idSet.next();
        long verId = idSet.getLong("generated_key");
        DbUtils.close(idSet);
        DbUtils.close(ps);

        // 更新version
        version.setId(verId);

        if (version.getMeta() != null && !version.getMeta().isEmpty()) {
            // 生成meta信息
            sql = "insert into t_table_meta(ver_id,column_name,column_id,original_ser,data_type,data_length,data_precision," +
                    "data_scale,nullable,is_pk,pk_position,alter_time,char_length,char_used,internal_column_id, " +
                    "hidden_column, virtual_column, original_column_name, comments, default_value) " +
                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

            ps = conn.prepareStatement(sql);
            List<MetaWrapper.MetaCell> columns = version.getMeta().getColumns();
            for (MetaWrapper.MetaCell column : columns) {
                ps.setLong(1, verId);
                ps.setString(2, column.getColumnName());
                ps.setInt(3, column.getColumnId());
                ps.setInt(4, version.getInnerVersion());
                ps.setString(5, column.getDataType());
                ps.setLong(6, column.getDataLength());
                ps.setInt(7, column.getDataPrecision());
                ps.setInt(8, column.getDataScale());
                ps.setString(9, column.getNullAble());
                ps.setString(10, column.getIspk());
                ps.setInt(11, column.getPkPosition());
                ps.setTimestamp(12, column.getDdlTime());
                ps.setInt(13, column.getCharLength());
                ps.setString(14, column.getCharUsed());
                ps.setInt(15, column.getInternalColumnId());
                ps.setString(16, column.getHiddenColumn());
                ps.setString(17, column.getVirtualColumn());
                ps.setString(18, column.getOriginalColumnName());
                ps.setString(19, column.getComments());
                ps.setString(20, column.getDefaultValue());
                ps.addBatch();
            }
            ps.executeBatch();
        }

        updateTableVerHistoryNotice(conn, version.getTableId());

        ps = conn.prepareStatement("update t_data_tables set ver_id = ? where id = ?");
        ps.setLong(1, verId);
        ps.setLong(2, version.getTableId());
        ps.executeUpdate();

        conn.commit();

    } catch (Exception e) {
        if (conn != null) conn.rollback();
        logger.error("create meta and version error", e);
        throw e;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}