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:edumsg.core.PostgresConnection.java

public static void disconnect(ResultSet rs, PreparedStatement statment, Connection conn, Statement query) {
    if (rs != null) {
        try {//from   w w w .j a  v a2s .c  o m
            rs.close();
        } catch (SQLException e) {
        }
    }
    if (statment != null) {
        try {
            statment.close();
        } catch (SQLException e) {
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
        }
    }

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

From source file:gridool.db.DBInsertOperation.java

private static void executeInsertQuery(@Nonnull final Connection conn, @Nonnull final String sql,
        @Nonnull final DBRecord[] records) throws SQLException {
    final PreparedStatement stmt = conn.prepareStatement(sql);
    try {//  ww  w.  j av  a  2s . c  o m
        for (final DBRecord rec : records) {
            rec.writeFields(stmt);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } finally {
        stmt.close();
    }
}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;//ww w  .ja v a 2 s  .  c  o m
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:com.concursive.connect.web.modules.activity.utils.ProjectHistoryUtils.java

public static int findNextThreadPosition(Connection db, ProjectHistory parentProjectHistory)
        throws SQLException {
    int count = 0;
    PreparedStatement pst = db
            .prepareStatement("SELECT count(*) AS ccount " + "FROM project_history " + "WHERE lineage LIKE ? ");
    pst.setString(1, parentProjectHistory.getLineage() + parentProjectHistory.getId() + "/%");
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        count = rs.getInt("ccount");
    }//from   ww w  . j a v  a 2s . co  m
    rs.close();
    pst.close();
    return (parentProjectHistory.getThreadPosition() + count + 1);
}

From source file:com.concursive.connect.web.modules.upgrade.utils.UpgradeUtils.java

/**
 * Records a database version as being executed
 *
 * @param db      The feature to be added to the Version attribute
 * @param version The feature to be added to the Version attribute
 * @throws SQLException Description of the Exception
 *///ww w. ja va2s. co  m
public static void addVersion(Connection db, String version) throws SQLException {
    // Add the specified version
    PreparedStatement pst = db.prepareStatement(
            "INSERT INTO database_version " + "(script_filename, script_version) VALUES (?, ?) ");
    pst.setString(1, DatabaseUtils.getTypeName(db) + "_" + version);
    pst.setString(2, version);
    pst.execute();
    pst.close();
}

From source file:com.autentia.tnt.bill.migration.support.MigratedInformationRecoverer.java

private static void liberaConexion(Connection con, PreparedStatement stmt, ResultSet rs) {
    if (rs != null) {
        try {/*  w  ww  .  j  av  a 2 s  .  co  m*/
            rs.close();
        } catch (SQLException sqlex) {
            log.error("Error al liberar el ResultSet", sqlex);
        }
    }

    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException sqlex) {
            log.error("Error al liberar el Statement", sqlex);
        }
    }

    if (con != null) {
        try {
            con.close();
        } catch (SQLException sqlex) {
            log.error("Error al liberar la conexin", sqlex);
        }
    }
}

From source file:com.concursive.connect.web.modules.activity.utils.ProjectHistoryUtils.java

public static int findNextPosition(Connection db, int projectHistoryId) throws SQLException {
    int position = 0;
    PreparedStatement pst = db.prepareStatement("SELECT max(position) AS position " + "FROM project_history "
            + "WHERE history_id = ? OR top_id = ? ");
    pst.setInt(1, projectHistoryId);/*w  w  w. ja va2  s  .  com*/
    pst.setInt(2, projectHistoryId);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        position = rs.getInt("position");
    }
    rs.close();
    pst.close();
    return (position + 1);
}

From source file:com.chaosinmotion.securechat.server.commands.RemoveDevice.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String deviceid = requestParams.optString("deviceid");

    /*//from  ww  w.j  a v  a  2  s  .  co m
     * Delete device. We only delete if it is also ours.
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Devices " + "WHERE userid = ? AND deviceuuid = ?");
        ps.setInt(1, userinfo.getUserID());
        ps.setString(2, deviceid);
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

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

public static void addPoints(L2Player player, int bossId, int points) {
    final Map<Integer, Integer> pointsByBossId = getList(player.getObjectId());

    points += pointsByBossId.containsKey(bossId) ? pointsByBossId.get(bossId).intValue() : 0;

    pointsByBossId.put(bossId, points);/*w  w  w.  j av  a  2 s .  co  m*/

    Connection con = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement;
        statement = con.prepareStatement(
                "REPLACE INTO character_raid_points (`charId`,`boss_id`,`points`) VALUES (?,?,?)");
        statement.setInt(1, player.getObjectId());
        statement.setInt(2, bossId);
        statement.setInt(3, points);
        statement.executeUpdate();
        statement.close();
    } catch (Exception e) {
        _log.fatal("could not update char raid points:", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:Main.java

public static String getCLOB(int id) throws Exception {
    Connection conn = null;/*w  w  w.j  av  a2  s  . c om*/
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT clobData FROM tableName WHERE id = ?";

    try {
        conn = getConnection();
        pstmt = conn.prepareStatement(query);
        pstmt.setInt(1, id);
        rs = pstmt.executeQuery();
        rs.next();
        Clob clob = rs.getClob(1);
        // materialize CLOB onto client
        String wholeClob = clob.getSubString(1, (int) clob.length());
        return wholeClob;
    } finally {
        rs.close();
        pstmt.close();
        conn.close();
    }
}