當前位置: 首頁>>代碼示例>>Java>>正文


Java DbUtils類代碼示例

本文整理匯總了Java中org.apache.commons.dbutils.DbUtils的典型用法代碼示例。如果您正苦於以下問題:Java DbUtils類的具體用法?Java DbUtils怎麽用?Java DbUtils使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


DbUtils類屬於org.apache.commons.dbutils包,在下文中一共展示了DbUtils類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: migrateOrCreateIfNotExists

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
public static boolean migrateOrCreateIfNotExists(String dbname) {
    String dbpath = getDbPath(dbname);
    String jdbcurl = "jdbc:h2:file:" + dbpath + ";DB_CLOSE_ON_EXIT=FALSE";
    LOG.info("new jdbcurl = {}", jdbcurl);
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(jdbcurl, "sa", "");

        DataSource ds = new CustomFlywayDataSource(new PrintWriter(System.out), conn);
        Flyway flyway = new Flyway();
        flyway.setDataSource(ds);
        // explicitly set h2db driver loaded (= including this jar file) class loader
        flyway.setClassLoader(conn.getClass().getClassLoader());
        flyway.migrate();
        LOG.info("db[{}] migration success", dbname);

        // may be already closed -> reconnect.
        DbUtils.closeQuietly(conn);
        conn = DriverManager.getConnection(jdbcurl, "sa", "");

        QueryRunner r = new QueryRunner();
        Long cnt = r.query(conn, "select count(*) from PROXY_HISTORY", new ScalarHandler<Long>());
        LOG.info("db[{}] open/creation success(select count(*) from logtable returns {})", dbname, cnt);

        return true;
    } catch (SQLException e) {
        LOG.error("db[" + dbname + "] open/migrate/creation error", e);
        return false;
    } finally {
        DbUtils.closeQuietly(conn);
    }
}
 
開發者ID:SecureSkyTechnology,項目名稱:burpextender-proxyhistory-webui,代碼行數:33,代碼來源:DataStore.java

示例2: main

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
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);
		}

	}
 
開發者ID:v5developer,項目名稱:maven-framework-project,代碼行數:23,代碼來源:MapListHandlerExample.java

示例3: main

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
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);
		}

	}
 
開發者ID:v5developer,項目名稱:maven-framework-project,代碼行數:26,代碼來源:BeanHandlerExample.java

示例4: getConnection

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
public static Connection getConnection(String dbname) throws SQLException {
    String dbpath = getDbPath(dbname);
    String jdbcurl = "jdbc:h2:file:" + dbpath + ";DB_CLOSE_ON_EXIT=FALSE";
    LOG.info("connect jdbcurl = {}", jdbcurl);
    Connection conn = DriverManager.getConnection(jdbcurl, "sa", "");

    DataSource ds = new CustomFlywayDataSource(new PrintWriter(System.out), conn);
    Flyway flyway = new Flyway();
    flyway.setDataSource(ds);
    // explicitly set h2db driver loaded (= including this jar file) class loader
    flyway.setClassLoader(conn.getClass().getClassLoader());
    flyway.migrate();
    LOG.info("db[{}] migration success", dbname);

    // may be already closed -> reconnect.
    DbUtils.closeQuietly(conn);
    conn = DriverManager.getConnection(jdbcurl, "sa", "");

    return conn;
}
 
開發者ID:SecureSkyTechnology,項目名稱:burpextender-proxyhistory-webui,代碼行數:21,代碼來源:DataStore.java

示例5: getNewToolContentId

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
private long getNewToolContentId(long newToolId, Connection conn) throws DeployException {
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("INSERT INTO lams_tool_content (tool_id) VALUES (?)");
    stmt.setLong(1, newToolId);
    stmt.execute();
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM lams_tool_content");
    results = stmt.executeQuery();
    if (results.next()) {
	return results.getLong("LAST_INSERT_ID()");
    } else {
	throw new DeployException("No tool content id found");
    }

} catch (SQLException sqlex) {
    throw new DeployException("Could not get new tool content id", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:23,代碼來源:ToolDBDeployTask.java

示例6: runLibraryScript

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
private long runLibraryScript(final String scriptSQL, final Connection conn) throws DeployException {
runScript(scriptSQL, conn);
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM lams_learning_library");
    results = stmt.executeQuery();
    if (results.next()) {
	return results.getLong("LAST_INSERT_ID()");
    } else {
	throw new DeployException("Could not get learning_library_id");
    }
} catch (SQLException sqlex) {
    throw new DeployException("Failed to run learning library script", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}

   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:21,代碼來源:ToolDBDeployTask.java

示例7: runToolInsertScript

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
private long runToolInsertScript(final String scriptSQL, final Connection conn) throws DeployException {
runScript(scriptSQL, conn);
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM lams_tool");
    results = stmt.executeQuery();
    if (results.next()) {
	return results.getLong("LAST_INSERT_ID()");
    } else {
	throw new DeployException("Could not get learning_library_id");
    }
} catch (SQLException sqlex) {
    throw new DeployException("Failed to run tool insert script", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}

   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:21,代碼來源:ToolDBDeployTask.java

示例8: queryTool

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
public String queryTool(String toolSig, String column) {
Connection conn = getConnection();
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn
	    .prepareStatement("select " + column + " from lams_tool where tool_signature= \"" + toolSig + "\"");
    System.out.println("SQL stmt: " + stmt);
    results = stmt.executeQuery();

    if (results.first()) {
	return results.getString(column);

    }
} catch (SQLException se) {

    throw new DeployException("Could not get entry from lams_tool: " + column + "\n" + se.getMessage());

} finally {
    DbUtils.closeQuietly(stmt);
}
return "ERROR";
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:24,代碼來源:ToolDBUpdater.java

示例9: executeStatements

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
/**
    * Executes an array of statements againt a connection.
    * Note that it will *WILL NOT* close the connection, commit or roll back.
    */
   protected void executeStatements(String[] statements, Connection newConn) throws DeployException {
Statement stmt = null;
try {
    stmt = newConn.createStatement();
    for (int i = 0, length = statements.length; i < length; i++) {
	stmt.addBatch(statements[i]);
    }

    stmt.executeBatch();

} catch (SQLException sqlex) {
    throw new DeployException("Could not execute statements", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
}
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:21,代碼來源:ScriptRunner.java

示例10: getToolId

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
/**
    * Looks up current tool installations for the tool with <code>toolSignature</code>
    * The tool_id for the tool with the matching tool signature will be returned.
    * 
    * @param toolSignature
    * @param conn
    * @return
    */
   public long getToolId(String toolSignature, Connection conn) {
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("SELECT tool_id FROM lams_tool WHERE tool_signature=?");
    stmt.setString(1, toolSignature);
    stmt.execute();

    results = stmt.executeQuery();
    if (results.next()) {
	return results.getLong("tool_id");
    } else {
	throw new DeployException("Tool id for tool signature " + toolSignature + " not found.");
    }

} catch (SQLException sqlex) {
    throw new DeployException("Tool id for tool signature " + toolSignature + " not found.", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:31,代碼來源:LibraryDBDeployTask.java

示例11: runLibraryScript

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
/**
    * Runs the sql statements and will return the last inserted id from the particular
    * table.
    * 
    * @param scriptSQL
    *            The sql to run
    * @param conn
    * @param tablename
    *            The table which to query for the last inserted id.
    * @return the last inserted id from <code>tablename</code>
    * @throws DeployException
    */
   private long runLibraryScript(final String scriptSQL, final Connection conn, String tablename)
    throws DeployException {
runScript(scriptSQL, conn);
PreparedStatement stmt = null;
ResultSet results = null;
try {
    stmt = conn.prepareStatement("SELECT LAST_INSERT_ID() FROM " + tablename);
    results = stmt.executeQuery();
    if (results.next()) {
	return results.getLong("LAST_INSERT_ID()");
    } else {
	throw new DeployException("Could not get the last inserted id from table " + tablename);
    }
} catch (SQLException sqlex) {
    throw new DeployException("Failed to run learning library script", sqlex);
} finally {
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(results);
}

   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:34,代碼來源:LibraryDBDeployTask.java

示例12: query

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
public <T> T query(Connection conn, String sql, ResultSetHandler<T> resultSetHandler) {
    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = conn.createStatement();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing query on {}: {}", displayConnection(conn), sql);
        }
        resultSet = statement.executeQuery(sql);
        return resultSetHandler.handle(resultSet);
    } catch (SQLException e) {
        throw new DataAccessException(e);
    } finally {
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(statement);
    }
}
 
開發者ID:goldmansachs,項目名稱:obevo,代碼行數:18,代碼來源:JdbcHelper.java

示例13: validateStep2

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
private void validateStep2(DataSource ds, String physicalSchemaStr, JdbcHelper jdbc) throws Exception {
    List<Map<String, Object>> results;
    Connection conn = ds.getConnection();
    try {
        results = jdbc.queryForList(conn, "select * from " + physicalSchemaStr + "TestTable order by idField");
    } finally {
        DbUtils.closeQuietly(conn);
    }

    assertEquals(5, results.size());
    this.validateResultRow(results.get(0), 1, "str1", 0);
    this.validateResultRow(results.get(1), 3, "str3Changed", 0);
    this.validateResultRow(results.get(2), 4, "str4", 0);
    this.validateResultRow(results.get(3), 5, "str5", 0);
    this.validateResultRow(results.get(4), 6, "str6", 0);
}
 
開發者ID:goldmansachs,項目名稱:obevo,代碼行數:17,代碼來源:MsSqlDeployerMainIT.java

示例14: testDeploy

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
@Test
public void testDeploy() throws Exception {
    getAppContext.valueOf(1)
            .cleanEnvironment()
            .deploy();

    // ensuring that we can modify
    DbDeployerAppContext dbDeployerAppContext = getAppContext.valueOf(2);
    dbDeployerAppContext
            .cleanEnvironment()
            .setupEnvInfra()
            .deploy();

    JdbcHelper jdbc = new JdbcHelper();

    Connection conn = ds.getConnection();
    try {
        List<Map<String, Object>> results = jdbc.queryForList(conn, "select * from " + dbDeployerAppContext.getEnvironment().getPhysicalSchema("schema1") + ".TABLE_A order by a_id");
        assertEquals(3, results.size());
        this.validateResults(results.get(0), 2, 3, "fasdfasd", "2013-02-02 11:11:11.65432", 9);
        this.validateResults(results.get(1), 3, 4, "ABC", null, 9);
        this.validateResults(results.get(2), 4, 2, "ABC", "2012-01-01 12:12:12", null);
    } finally {
        DbUtils.closeQuietly(conn);
    }
}
 
開發者ID:goldmansachs,項目名稱:obevo,代碼行數:27,代碼來源:PostgreSqlDeployerIT.java

示例15: setupEnvInfra

import org.apache.commons.dbutils.DbUtils; //導入依賴的package包/類
@Override
public void setupEnvInfra(boolean failOnSetupException) {
    // will reenable this functionality at another time
    if (true) {
        return;
    }
    Connection conn = null;
    try {
        conn = ds.getConnection();
        for (PhysicalSchema schema : env.getPhysicalSchemas()) {
            createSchema(conn, schema);
        }
    } catch (SQLException e) {
        if (failOnSetupException) {
            throw new DataAccessException(e);
        } else {
            LOG.warn("Env Infra Setup connection failed", e);
            deployMetricsCollector.addMetric(DeployMetrics.WARNINGS_PREFIX + ".envInfraSetupConnectionFailure.oracle", true);
            return;
        }
    } finally {
        DbUtils.closeQuietly(conn);
    }
}
 
開發者ID:goldmansachs,項目名稱:obevo,代碼行數:25,代碼來源:OracleEnvironmentInfraSetup.java


注:本文中的org.apache.commons.dbutils.DbUtils類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。