List of usage examples for java.sql PreparedStatement close
void close() throws SQLException;
Statement
object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. From source file:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java
private void p0(final DataSource dataSource, String name, int threadCount) throws Exception { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await();/*from www . j a v a 2 s . c o m*/ for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL"); ResultSet rs = stmt.executeQuery(); rs.next(); rs.getInt(1); rs.close(); stmt.close(); conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } endLatch.countDown(); } }; thread.start(); } long startMillis = System.currentTimeMillis(); long startYGC = TestUtil.getYoungGC(); long startFullGC = TestUtil.getFullGC(); startLatch.countDown(); endLatch.await(); long millis = System.currentTimeMillis() - startMillis; long ygc = TestUtil.getYoungGC() - startYGC; long fullGC = TestUtil.getFullGC() - startFullGC; System.out.println("thread " + threadCount + " " + name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC); }
From source file:azkaban.jobtype.ReportalTeradataRunner.java
@Override protected void runReportal() throws Exception { System.out.println("Reportal Teradata: Setting up Teradata"); List<Exception> exceptions = new ArrayList<Exception>(); Class.forName("com.teradata.jdbc.TeraDriver"); String connectionString = props.getString("reportal.teradata.connection.string", null); String user = props.getString("reportal.teradata.username", null); String pass = props.getString("reportal.teradata.password", null); if (user == null) { System.out.println("Reportal Teradata: Configuration incomplete"); throw new RuntimeException("The reportal.teradata.username variable was not defined."); }//from w ww. ja v a 2s . c om if (pass == null) { System.out.println("Reportal Teradata: Configuration incomplete"); throw new RuntimeException("The reportal.teradata.password variable was not defined."); } DataSource teraDataSource = new TeradataDataSource(connectionString, user, pass); Connection conn = teraDataSource.getConnection(); String sqlQueries[] = cleanAndGetQueries(jobQuery, proxyUser); int numQueries = sqlQueries.length; for (int i = 0; i < numQueries; i++) { try { String queryLine = sqlQueries[i]; // Only store results from the last statement if (i == numQueries - 1) { PreparedStatement stmt = prepareStatement(conn, queryLine); stmt.execute(); ResultSet rs = stmt.getResultSet(); outputQueryResult(rs, outputStream); stmt.close(); } else { try { PreparedStatement stmt = prepareStatement(conn, queryLine); stmt.execute(); stmt.close(); } catch (NullPointerException e) { // An empty query (or comment) throws a NPE in JDBC. Yay! System.err.println( "Caught NPE in execute call because report has a NOOP query: " + queryLine); } } } catch (Exception e) { // Catch and continue. Delay exception throwing until we've run all queries in this task. System.out.println("Reportal Teradata: SQL query failed. " + e.getMessage()); e.printStackTrace(); exceptions.add(e); } } if (exceptions.size() > 0) { throw new CompositeException(exceptions); } System.out.println("Reportal Teradata: Ended successfully"); }
From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java
/** * Setup Datasource and create table for test. * * @throws Exception //from ww w .j a v a 2 s .c om */ @Before public void setUp() throws Exception { // DataSource Setup, apache commons dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:testdb"); dataSource.setUsername("sa"); dataSource.setPassword(""); // drop table if exists Connection conn = dataSource.getConnection(); Statement st = conn.createStatement(); st.execute(DROP_TEST_TABLE); conn.commit(); st.close(); conn.close(); // create table conn = dataSource.getConnection(); st = conn.createStatement(); st.execute(CREATE_TEST_TABLE); conn.commit(); st.close(); conn.close(); // fill with values conn = dataSource.getConnection(); // prevent auto commit for batching conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement(INSERT); // fill with values for (int i = 0; i < EXPECTED_COUNT; i++) { ps.setString(1, String.valueOf(i)); ps.addBatch(); } ps.executeBatch(); conn.commit(); ps.close(); conn.close(); }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataStructureHandler.java
private <E> void executeStatement(TableMetadata<E> tableMetadata, Statements.Definition statementType, Metadata metadata) {// w w w. j a va 2 s . c o m try { final Statement statement = session.getDatabaseDialect().getStatementBuilderContext() .getDefinitionStatementBuilder(statementType).getStatement(tableMetadata, metadata); if (statement.getSql().trim().isEmpty()) { return; } final Connection connection = session.getConnection(); final PreparedStatement preparedStatement = statement.prepare(connection); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } catch (SQLException e) { throw new UnsuccessfulOperationError("Failed to execute statement: " + statementType, e); } }
From source file:net.sf.jdbcwrappers.trim.TrimmingTest.java
@Test public void testPreparedStatement() throws SQLException { PreparedStatement statement = connection.prepareStatement("SELECT * FROM TEST WHERE INT_COL=?"); try {//from w w w .ja va 2 s . c o m statement.setInt(1, 12); ResultSet rs = statement.executeQuery(); rs.next(); assertEquals("test", rs.getString(2)); assertEquals("test", rs.getString("CHAR_COL")); } finally { statement.close(); } }
From source file:com.hangum.tadpole.rdb.core.editors.main.utils.plan.CubridExecutePlanUtils.java
/** * cubrid execute plan//ww w .j a va 2 s. co m * * @param userDB * @param reqQuery * @return * @throws Exception */ public static String plan(UserDBDAO userDB, final RequestQuery reqQuery) throws Exception { String sql = reqQuery.getSql(); if (!sql.toLowerCase().startsWith("select")) { logger.error("[cubrid execute plan ]" + sql); throw new Exception("This statment not select. please check."); } Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; try { conn = TadpoleSQLManager.getInstance(userDB).getDataSource().getConnection(); conn.setAutoCommit(false); // auto commit? false . sql = StringUtils.trim(sql).substring(6); if (logger.isDebugEnabled()) logger.debug("[qubrid modifying query]" + sql); sql = "select " + RECOMPILE + sql; pstmt = conn.prepareStatement(sql); if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.PREPARED_STATEMENT) { final Object[] statementParameter = reqQuery.getStatementParameter(); for (int i = 1; i <= statementParameter.length; i++) { pstmt.setObject(i, statementParameter[i - 1]); } } ((CUBRIDStatement) pstmt).setQueryInfo(true); rs = pstmt.executeQuery(); String plan = ((CUBRIDStatement) pstmt).getQueryplan(); // ? . if (logger.isDebugEnabled()) logger.debug("cubrid plan text : " + plan); return plan; } finally { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } }
From source file:eu.optimis.ip.gui.client.resources.Accounting.java
public void addUser(String name, String password) { try {//from ww w. j a v a 2s. com start(); PreparedStatement p = connection .prepareStatement("INSERT INTO Users (userName, password) VALUES (?, ?);"); p.setString(1, name); p.setString(2, password); p.executeUpdate(); connection.commit(); p.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex.getMessage(), ex); } finally { close(); } }
From source file:com.wso2telco.util.DBConnection.java
/** * Close the database connection./*w w w. ja v a 2 s . c o m*/ * * @param connection Connection instance used by the method call * @param statement prepared Statement used by the method call * @param resultSet result set which is used by the method call */ public void close(Connection connection, PreparedStatement statement, ResultSet resultSet) { try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (Exception e) { logger.error("Error occurred while Closing the Connection"); } }
From source file:com.l2jfree.gameserver.instancemanager.RecommendationManager.java
/** * <B>Create an entry in `character_recommend_data`</B>.<BR> * Called just after character creation, but may be also called when restoring player's * evaluation data and the entry is missing. * @param player The newly created player *///from w w w. j av a 2s . com public void onCreate(L2Player player) { Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement ps = con.prepareStatement(ADD_RECOMMENDATION_INFO); ps.setInt(1, player.getObjectId()); ps.setLong(2, nextUpdate - DAY); ps.executeUpdate(); ps.close(); } catch (SQLException e) { _log.error("Failed creating recommendation data for " + player.getName() + "!", e); } finally { L2DatabaseFactory.close(con); } }
From source file:com.ywang.alone.handler.task.AuthTask.java
/** * { 'key':'2597aa1d37d432a','uid':'1020293' } * /*from www . ja va 2s.c o m*/ * @param param * @return */ private static String getUserInfo(String msg) { JSONObject jsonObject = AloneUtil.newRetJsonObject(); JSONObject param = JSON.parseObject(msg); String token = param.getString("key"); String userId = null; if (StringUtils.isEmpty(token)) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); return jsonObject.toJSONString(); } Jedis jedis = JedisUtil.getJedis(); Long tokenTtl = jedis.ttl("TOKEN:" + token); if (tokenTtl == -1) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); } else { userId = jedis.get("TOKEN:" + token); LoggerUtil.logMsg("uid is " + userId); } JedisUtil.returnJedis(jedis); if (StringUtils.isEmpty(userId)) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); return jsonObject.toJSONString(); } String aimUid = param.getString("uid");//uid?? if (StringUtils.isEmpty(aimUid)) { aimUid = userId; } DruidPooledConnection conn = null; PreparedStatement stmt = null; JSONObject data = new JSONObject(); try { conn = DataSourceFactory.getInstance().getConn(); conn.setAutoCommit(false); stmt = conn.prepareStatement("SELECT * FROM USERBASE WHERE USER_ID = ?", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, aimUid); ResultSet userInfoRs = stmt.executeQuery(); if (userInfoRs.next()) { UserInfo userInfo = new UserInfo(); userInfo.setRegTime(userInfoRs.getLong("REG_TIME")); userInfo.setUserId(userInfoRs.getString("USER_ID")); userInfo.setAvatar(userInfoRs.getString("AVATAR")); userInfo.setNickName(userInfoRs.getString("NICKNAME")); userInfo.setAge(userInfoRs.getString("AGE")); userInfo.setHoroscope(userInfoRs.getString("HORO_SCOPE")); userInfo.setHeight(userInfoRs.getString("HEIGHT")); userInfo.setWeight(userInfoRs.getString("WEIGHT")); userInfo.setRoleName(userInfoRs.getString("ROLENAME")); userInfo.setAffection(userInfoRs.getString("AFFECTION")); userInfo.setPurpose(userInfoRs.getString("PURPOSE")); userInfo.setEthnicity(userInfoRs.getString("ETHNICITY")); userInfo.setOccupation(userInfoRs.getString("OCCUPATION")); userInfo.setLivecity(userInfoRs.getString("LIVECITY")); userInfo.setLocation(userInfoRs.getString("LOCATION")); userInfo.setTravelcity(userInfoRs.getString("TRAVELCITY")); userInfo.setMovie(userInfoRs.getString("MOVIE")); userInfo.setMusic(userInfoRs.getString("MUSIC")); userInfo.setBooks(userInfoRs.getString("BOOKS")); userInfo.setFood(userInfoRs.getString("FOOD")); userInfo.setOthers(userInfoRs.getString("OTHERS")); userInfo.setIntro(userInfoRs.getString("INTRO")); userInfo.setLastLoginTime(userInfoRs.getLong("LAST_LOGIN_TIME")); // userInfo.setMessagePwd(userInfoRs // .getString("MESSAGE_PWD")); userInfo.setMessageUser(userInfoRs.getString("MESSAGE_USER")); // userInfo.setOnline("1"); data.put("userInfo", JSONObject.toJSON(userInfo)); PreparedStatement pstmt = conn.prepareStatement( "SELECT * FROM uploads WHERE USER_ID = ? and ENABLING=1", Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, aimUid); ResultSet pSet = pstmt.executeQuery(); JSONArray jsonArray = new JSONArray(); while (pSet.next()) { jsonArray.add(pSet.getString("PHOTO_PATH")); } data.put("photos", JSONObject.toJSON(jsonArray)); jsonObject.put("data", JSONObject.toJSON(data)); pSet.close(); pstmt.close(); } else { jsonObject.put("ret", Constant.RET.SYS_ERR); jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR); jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR); } userInfoRs.close(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { LoggerUtil.logServerErr(e); jsonObject.put("ret", Constant.RET.SYS_ERR); jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR); jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR); } finally { try { if (null != stmt) { stmt.close(); } if (null != conn) { conn.close(); } } catch (SQLException e) { LoggerUtil.logServerErr(e.getMessage()); } } return jsonObject.toJSONString(); }