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:com.flexive.core.Database.java

/**
 * Store a FxString in a translation table that only consists of one(!) translation column
 *
 * @param string     string to be stored
 * @param con        existing connection
 * @param table      storage table//  w w w. j  a  va 2 s  .c  o  m
 * @param dataColumn name of the data column
 * @param idColumn   name of the id column
 * @param id         id of the given string
 * @throws SQLException if a database error occured
 */
public static void storeFxString(FxString string, Connection con, String table, String dataColumn,
        String idColumn, long id) throws SQLException {
    if (!string.isMultiLanguage()) {
        throw new FxInvalidParameterException("string", LOG, "ex.db.fxString.store.multilang", table)
                .asRuntimeException();
    }
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement("DELETE FROM " + table + ML + " WHERE " + idColumn + "=?");
        ps.setLong(1, id);
        ps.execute();
        ps.close();
        if (string.getTranslatedLanguages().length > 0) {
            ps = con.prepareStatement("INSERT INTO " + table + ML + " (" + idColumn + ",LANG,DEFLANG,"
                    + dataColumn + ") VALUES (?,?,?,?)");
            ps.setLong(1, id);
            String curr;
            for (long lang : string.getTranslatedLanguages()) {
                curr = string.getTranslation(lang);
                if (curr != null && curr.trim().length() > 0) {
                    ps.setInt(2, (int) lang);
                    ps.setBoolean(3, lang == string.getDefaultLanguage());
                    ps.setString(4, curr);
                    ps.executeUpdate();
                }
            }
        }
    } finally {
        if (ps != null)
            ps.close();
    }
}

From source file:marytts.util.io.FileUtils.java

/**
 *  Close a PreparedStatement and a series of result sets.
 * Use this in a finally clause./*w  ww.j  ava2 s  . c  o  m*/
 * While closing the PreparedStatement supposedly closes it's resultsets,
 * i was told that some buggy implementations don't.
 * Exists because PreparedStatement and Resultet are only closeable on jdk 1.7
 */
public static void close(PreparedStatement ps, ResultSet... rs) {
    for (ResultSet c : rs) {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ex) {
                MaryUtils.getLogger(FileUtils.class.getName()).log(Level.WARN, "Couldn't close ResultSet.", ex);
            }
        }
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (Exception ex) {
            MaryUtils.getLogger(FileUtils.class.getName()).log(Level.WARN, "Couldn't close PreparedStatement.",
                    ex);
        }
    }
}

From source file:com.foxelbox.foxbukkit.database.DatabaseConnectionPool.java

private void _runSQL(Connection connection, String sql) throws SQLException {
    PreparedStatement stmt = connection.prepareStatement(sql);
    stmt.execute();/*from w  ww .j  a v  a  2s .  c o m*/
    stmt.close();
}

From source file:com.wso2.raspberrypi.Util.java

public static void updateRaspberryPi(RaspberryPi raspberryPi) {
    BasicDataSource ds = getBasicDataSource();
    Connection dbConnection = null;
    PreparedStatement prepStmt = null;
    try {//from  ww  w .j  a va 2 s .co  m
        dbConnection = ds.getConnection();
        prepStmt = dbConnection.prepareStatement("UPDATE RASP_PI SET blink=" + raspberryPi.isBlink()
                + ",reboot=" + raspberryPi.isReboot() + ",selected=" + raspberryPi.isSelected() + ",label='"
                + raspberryPi.getLabel() + "'" + " where mac='" + raspberryPi.getMacAddress() + "'");
        prepStmt.execute();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dbConnection != null) {
                dbConnection.close();
            }
            if (prepStmt != null) {
                prepStmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {/*from  w  ww  . j  a v a2 s . c o m*/
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:br.edu.claudivan.controledegastos.dao.utils.DatabaseUtils.java

public void closeConnection(Connection dbConnection, ResultSet queryResultSet, PreparedStatement queryStatement)
        throws SQLException {
    if (queryStatement != null) {
        queryStatement.close();
    }//w w w  .jav  a  2s  .com

    if (queryResultSet != null) {
        queryResultSet.close();
    }

    closeConnection(dbConnection);
}

From source file:de.static_interface.reallifeplugin.module.contract.database.table.ContractUsersTable.java

@Override
public void create() throws SQLException {
    String sql;/*from  w w w  .ja  v  a  2s .c  o  m*/

    switch (db.getType()) {
    case H2:
        sql = "CREATE TABLE IF NOT EXISTS " + getName() + " (" + "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
                + "uuid VARCHAR(36) NOT NULL" + ");";
        break;

    case MYSQL:
    default:
        sql = "CREATE TABLE IF NOT EXISTS `" + getName() + "` ("
                + "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY," + "`uuid` VARCHAR(36) NOT NULL" + ");";
        break;
    }

    PreparedStatement statement = db.getConnection().prepareStatement(sql);
    statement.executeUpdate();
    statement.close();
}

From source file:genericepayadmin.AddIpBean.java

public static ArrayList getTreasury(Connection con) throws Exception {
    PreparedStatement ps = null;
    ResultSet rs = null;//  ww w  .j  a  v a 2 s. c  o  m
    ArrayList al = new ArrayList();

    try {
        String sql = "select wbser.active, wbser.id, gdep.dept_name, wbser.ipaddress,wbser.checksum from webservice_validator wbser,generic_dept gdep "
                + " where gdep.DEPT_ID=wbser.deptid ";
        ps = con.prepareStatement(sql);

        rs = ps.executeQuery();
        while (rs.next()) {
            AddIpBean tbean = new AddIpBean();
            tbean.setId(rs.getString("id"));
            tbean.setDept_name(rs.getString("dept_name"));
            tbean.setIpaddress(rs.getString("ipaddress"));
            tbean.setChecksum(rs.getString("checksum"));
            tbean.setStatus(rs.getString("active"));
            al.add(tbean);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        if (ps != null)
            ps.close();
        if (rs != null)
            rs.close();
    }
    return al;
}

From source file:com.sf.ddao.ops.UpdateSqlOperation.java

public boolean execute(Context context) throws Exception {
    try {/*from  w w w  . j a  v a2  s .  c o  m*/
        final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
        PreparedStatement preparedStatement = statementFactory.createStatement(context, false);
        int res = preparedStatement.executeUpdate();
        preparedStatement.close();
        if (method.getReturnType() == Integer.TYPE || method.getReturnType() == Integer.class) {
            callCtx.setLastReturn(res);
        }
        return CONTINUE_PROCESSING;
    } catch (Exception t) {
        throw new DaoException("Failed to execute sql operation for " + method, t);
    }
}

From source file:com.taobao.tddl.jdbc.group.integration.SpringTest.java

@Test
public void springTest() throws Exception {

    Connection conn = ds.getConnection();

    //Statementcrud
    Statement stmt = conn.createStatement();
    assertEquals(stmt.executeUpdate("insert into crud(f1,f2) values(10,'str')"), 1);
    assertEquals(stmt.executeUpdate("update crud set f2='str2'"), 1);
    ResultSet rs = stmt.executeQuery("select f1,f2 from crud");
    rs.next();//www  . j  a va  2s  .  c  om
    assertEquals(rs.getInt(1), 10);
    assertEquals(rs.getString(2), "str2");
    assertEquals(stmt.executeUpdate("delete from crud"), 1);
    rs.close();
    stmt.close();

    //PreparedStatementcrud
    String sql = "insert into crud(f1,f2) values(10,'str')";
    PreparedStatement ps = conn.prepareStatement(sql);
    assertEquals(ps.executeUpdate(), 1);
    ps.close();

    sql = "update crud set f2='str2'";
    ps = conn.prepareStatement(sql);
    assertEquals(ps.executeUpdate(), 1);
    ps.close();

    sql = "select f1,f2 from crud";
    ps = conn.prepareStatement(sql);
    rs = ps.executeQuery();
    rs.next();
    assertEquals(rs.getInt(1), 10);
    assertEquals(rs.getString(2), "str2");
    rs.close();
    ps.close();

    sql = "delete from crud";
    ps = conn.prepareStatement(sql);
    assertEquals(ps.executeUpdate(), 1);
    ps.close();

    conn.close();
}