Example usage for java.sql PreparedStatement close

List of usage examples for java.sql PreparedStatement close

Introduction

In this page you can find the example usage for java.sql PreparedStatement close.

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:net.sf.sprockets.sql.Statements.java

/**
 * Execute the query, get the int value in the first row and column of the result set, and close
 * the statement./*from  w ww. j a  v  a  2 s .c  om*/
 * 
 * @param stmt
 *            must already have parameters set
 * @return {@link Integer#MIN_VALUE} if the result set is empty
 */
public static int firstInt(PreparedStatement stmt) throws SQLException {
    ResultSet rs = stmt.executeQuery();
    int i = rs.next() ? rs.getInt(1) : Integer.MIN_VALUE;
    stmt.close();
    return i;
}

From source file:com.l2jfree.gameserver.instancemanager.RaidPointsManager.java

public static void cleanUp() {
    Connection con = null;// w  w  w .  ja v a2 s  .  c  om
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement;
        statement = con.prepareStatement("DELETE from character_raid_points WHERE charId > 0");
        statement.executeUpdate();
        statement.close();
        _list.clear();
    } catch (Exception e) {
        _log.fatal("could not clean raid points: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:net.sf.sprockets.sql.Statements.java

/**
 * Execute the insert statement, get the first generated key as a long, and close the statement.
 * /*from   w  w  w  .  j a v a 2  s .  c o  m*/
 * @param stmt
 *            must have been created with {@link Statement#RETURN_GENERATED_KEYS} and already
 *            have parameters set
 * @return 0 if the statement did not generate any keys
 */
public static long firstLongKey(PreparedStatement stmt) throws SQLException {
    stmt.execute();
    ResultSet rs = stmt.getGeneratedKeys();
    long l = rs.next() ? rs.getLong(1) : 0L;
    stmt.close();
    return l;
}

From source file:mitll.xdata.dataset.kiva.ingest.KivaIngest.java

@SuppressWarnings("unchecked")
public static void loadTable(String tableName, String schemaFilename, String dataFilename) throws Exception {
    Object[] temp = processSchema(schemaFilename);
    List<String> names = (List<String>) temp[0];
    List<String> types = (List<String>) temp[1];

    Class.forName("org.h2.Driver");
    Connection connection = DriverManager.getConnection("jdbc:h2:tcp://localhost//h2data/kiva/kiva", "sa", "");

    String createSQL = createCreateSQL(tableName, names, types);
    String insertSQL = createInsertSQL(tableName, names);

    PreparedStatement statement = connection.prepareStatement(createSQL);
    statement.executeUpdate();//from   ww w  .jav  a2s . c  o m
    statement.close();

    statement = connection.prepareStatement(insertSQL);

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(dataFilename), "UTF-8"));
    String line = null;
    int count = 0;
    long t0 = System.currentTimeMillis();
    while ((line = br.readLine()) != null) {
        count++;
        List<String> values = split(line, "\t");
        executePreparedStatement(statement, types, values);
        if (count % 10000 == 0) {
            System.out.println(
                    "count = " + count + "; " + (System.currentTimeMillis() - 1.0 * t0) / count + " ms/insert");
        }
    }
    br.close();

    statement.close();

    long t1 = System.currentTimeMillis();
    System.out.println("total count = " + count);
    System.out.println("total time = " + ((t1 - t0) / 1000.0) + " s");
    System.out.println((t1 - 1.0 * t0) / count + " ms/insert");
    System.out.println((1000.0 * count / (t1 - 1.0 * t0)) + " inserts/s");
}

From source file:cn.edu.zju.acm.onlinejudge.persistence.sql.Database.java

public static void dispose(PreparedStatement ps) {
    if (ps != null) {
        try {/*www  . j  av  a  2s  . c  o m*/
            ps.close();
        } catch (Exception e) {
        }
    }
}

From source file:Emporium.Controle.ContrVpne.java

public static boolean inserirVpne(String sql, String nomeBD) {
    Connection conn = Conexao.conectar(nomeBD);
    try {//from   www. j  av a2s  .  com
        PreparedStatement valores = conn.prepareStatement(sql);
        valores.executeUpdate();
        valores.close();
        return true;
    } catch (SQLException e) {
        Logger.getLogger(ContrPreVendaImporta.class.getName()).log(Level.WARNING, e.getMessage(), e);
        return false;
    } finally {
        Conexao.desconectar(conn);
    }
}

From source file:Main.java

public static long writeJavaObject(Connection conn, Object object) throws Exception {
    String className = object.getClass().getName();
    PreparedStatement pstmt = conn.prepareStatement(WRITE_OBJECT_SQL);
    pstmt.setString(1, className);/*from   ww w.  ja va 2  s.  c o  m*/
    pstmt.setObject(2, object);
    pstmt.executeUpdate();
    ResultSet rs = pstmt.getGeneratedKeys();
    int id = -1;
    if (rs.next()) {
        id = rs.getInt(1);
    }
    rs.close();
    pstmt.close();
    return id;
}

From source file:com.ibm.research.rdf.store.runtime.service.sql.UpdateHelper.java

private static void closeSQLObjects(PreparedStatement stmt, ResultSet rs) {
    try {// w w  w.ja  v  a 2 s.  c  om
        if (rs != null)
            rs.close();
    } catch (SQLException e) {
    }

    try {
        if (stmt != null)
            stmt.close();
    } catch (SQLException e) {
    }
}

From source file:com.glaf.activiti.util.ExecutionUtils.java

@SuppressWarnings("unchecked")
public static void executeSqlUpdate(DelegateExecution execution, Expression sql) {
    CommandContext commandContext = Context.getCommandContext();

    ExecutionEntity executionEntity = commandContext.getExecutionEntityManager()
            .findExecutionById(execution.getId());
    String processDefinitionId = executionEntity.getProcessDefinitionId();
    ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessDefinitionEntityManager()
            .findProcessDefinitionById(processDefinitionId);
    String processName = processDefinitionEntity.getKey();

    Map<String, Object> params = new java.util.HashMap<String, Object>();

    Map<String, Object> variables = execution.getVariables();
    if (variables != null && variables.size() > 0) {
        Iterator<String> iterator = variables.keySet().iterator();
        while (iterator.hasNext()) {
            String variableName = iterator.next();
            if (params.get(variableName) == null) {
                Object value = execution.getVariable(variableName);
                params.put(variableName, value);
            }/*from www  .  jav  a 2s  .co  m*/
        }
    }

    params.put(Constants.BUSINESS_KEY, execution.getProcessBusinessKey());
    params.put("processInstanceId", execution.getProcessInstanceId());
    params.put("processDefinitionId", processDefinitionEntity.getId());
    params.put("processName", processName);
    params.put("now", new java.util.Date());

    if (sql != null) {
        String sqlx = sql.getExpressionText();

        if (sqlx.indexOf("#{tableName}") != -1) {
            String tableName = (String) execution.getVariable("tableName");
            if (StringUtils.isNotEmpty(tableName)) {
                sqlx = StringTools.replace(sqlx, "#{tableName}", tableName);
            }
        } else if (sqlx.indexOf("${tableName}") != -1) {
            String tableName = (String) execution.getVariable("tableName");
            if (StringUtils.isNotEmpty(tableName)) {
                sqlx = StringTools.replace(sqlx, "${tableName}", tableName);
            }
        }

        sqlx = StringTools.replaceIgnoreCase(sqlx, "${", "#{");

        List<Object> values = new java.util.ArrayList<Object>();
        SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sqlx, params);
        sqlx = sqlExecutor.getSql();
        if (sqlExecutor.getParameter() != null) {
            if (sqlExecutor.getParameter() instanceof List) {
                List<Object> list = (List<Object>) sqlExecutor.getParameter();
                values.addAll(list);
            }
        }

        logger.debug(sqlx);
        logger.debug(values);

        Connection con = null;
        try {
            con = commandContext.getDbSqlSession().getSqlSession().getConnection();
            PreparedStatement psmt = con.prepareStatement(sqlx);
            JdbcUtils.fillStatement(psmt, values);
            psmt.executeUpdate();
            psmt.close();
            psmt = null;
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

    }
}

From source file:com.skilrock.lms.common.db.DBConnect.java

public static void closePstmt(PreparedStatement pstm) {
    try {/*from w w w.ja v a  2  s .  c o  m*/
        if (pstm == null)
            logger.info("PreparedStatement Already Closed Or Empty");
        else
            pstm.close();
    } catch (SQLException ex) {
        logger.error("Problem While closing PreparedStatement");
        ex.printStackTrace();

    }
}