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.jernejerin.traffic.helper.TripOperations.java

/**
 * Truncate table./*from w  ww. j  a v  a 2  s. co m*/
 *
 * @param table table to truncate
 */
public static void truncateTable(String table) {
    //        LOGGER.log(Level.INFO, "Started inserting trip into DB for trip = " +
    //                trip.toString() + " from thread = " + Thread.currentThread());
    PreparedStatement truncateTable = null;
    Connection conn = null;
    try {
        // first we need to get connection from connection pool
        conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:taxi");

        // setting up prepared statement
        truncateTable = conn.prepareStatement("truncate " + table);
        truncateTable.execute();
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE,
                "Problem when truncating table = " + table + " from thread = " + Thread.currentThread());
    } finally {
        try {
            if (truncateTable != null)
                truncateTable.close();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Problem with closing prepared statement for truncating table = " + table
                    + " from thread = " + Thread.currentThread());
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Problem with closing connection from thread = " + Thread.currentThread());
        }
        //            LOGGER.log(Level.INFO, "Finished inserting ticket into DB for for ticket = " +
        //                    trip + " from thread = " + Thread.currentThread());
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get a list of all the users in the system.
 * @return an Arraylist of Users representing all the users in the system.
 *//*from  w w w  .  jav a 2  s.  com*/
public static ArrayList<User> getUserList() {
    ArrayList<User> list = new ArrayList<User>();

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            PreparedStatement getUserList = conn.prepareStatement(GET_USER_LIST);
            ResultSet userData = getUserList.executeQuery();

            while (userData.next()) {
                String username = userData.getString(Global.USER_NAME);
                list.add(getUserData(username));
            }
            userData.close();

            getUserList.close();
            conn.close();
        } catch (Exception e) {
            MetaDbHelper.logEvent(e);
        }
    }
    return list;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private static void closeStatement(SessionScope sessionScope, PreparedStatement ps) {
    if (ps != null) {
        if (!sessionScope.hasPreparedStatement(ps)) {
            try {
                ps.close();
            } catch (SQLException e) {
                // ignore
            }/* w  w w .j a  v a 2 s  .  c  om*/
        }
    }
}

From source file:at.becast.youploader.database.SQLite.java

public static void updatePlaylist(Item item) throws SQLException, IOException {
    PreparedStatement prest = null;
    String sql = "UPDATE `playlists` SET `name`=?,`image`=? WHERE `playlistid`=?";
    prest = c.prepareStatement(sql);// ww  w  . j av  a2  s.co m
    prest.setString(1, item.snippet.title);
    URL url = new URL(item.snippet.thumbnails.default__.url);
    InputStream is = null;
    is = url.openStream();
    byte[] imageBytes = IOUtils.toByteArray(is);
    prest.setBytes(2, imageBytes);
    prest.setString(3, item.id);
    prest.execute();
    prest.close();

}

From source file:es.tena.foundation.util.POIUtil.java

public static void generateXLS(String tabla, String filename, Connection conn, String encoding)
        throws SQLException {
    String query = "";
    try {/*from w w w  .j a  v a 2s  .  com*/
        query = "SELECT * FROM (" + tabla + ")";
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rset = stmt.executeQuery();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(filename);
        String sheetRef = sheet.getPackagePart().getPartName().getName();
        String template = "c:\\temp\\template_" + filename + ".xlsx";
        FileOutputStream os = new FileOutputStream(template);
        wb.write(os);
        os.close();

        File tmp = File.createTempFile("sheet", ".xml");
        Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), encoding);
        generate(fw, rset, encoding);
        rset.close();
        stmt.close();
        fw.close();

        FileOutputStream out = new FileOutputStream(
                "c:\\temp\\" + filename + sdf.format(calendario.getTime()) + ".xlsx");
        FileUtil.substitute(new File(template), tmp, sheetRef.substring(1), out);
        out.close();
        Logger.getLogger(POIUtil.class.getName()).log(Level.INFO, "Creado con exito {0}", filename);
    } catch (Exception ex) {
        ex.printStackTrace();
        Logger.getLogger(POIUtil.class.getName()).log(Level.SEVERE, null, query + "\n" + ex);
        System.out.println(query);
    } finally {
        conn.close();
    }
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Just uninstalls a single .jar file without deletion.
 * Eats any errors.//from w w w  .j  a  v a2  s  . c  o  m
 */
public static void uninstallJar(String jarFile) {
    PreparedStatement ps = null;
    try {
        Connection conn = DriverManager.getConnection("jdbc:default:connection");
        String name = jarFile.replaceAll("\\.jar", "");
        String query = "DROP JAR localdb.sys_network.\"" + name + "\" OPTIONS(1) CASCADE";
        ps = conn.prepareStatement(query);
        ps.execute();
    } catch (Throwable e) {
        //munch
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            //pass
        }
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Create a new user//  w w  w . j ava  2 s . c o  m
 * 
 * @param userName The username for the new user.
 * @param password The password for the new user.
 * @param type The type for the new user. ("admin" or "worker")
 * @return true if the user is added successfully, false otherwise
 */
public static boolean createUser(String userName, String password, String type, String authType) {
    if (MetaDbHelper.userExists(userName)) //duplicate user
        return false;

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            PreparedStatement createUser = conn.prepareStatement(CREATE_USER);

            createUser.setString(1, userName);
            createUser.setString(2, encryptPassword(password));
            createUser.setString(3, type);
            createUser.setString(4, authType);
            createUser.setLong(5, 0);

            createUser.executeUpdate();

            createUser.close();
            conn.close();
            return true;

        } catch (Exception e) {
            MetaDbHelper.logEvent(e);
        }
    }
    return false;
}

From source file:org.red5.webapps.admin.controllers.service.UserDAO.java

public static boolean addUser(String username, String hashedPassword) {
    boolean result = false;

    Connection conn = null;/*from  w  w  w.  j av  a  2  s  .  c  o m*/
    PreparedStatement stmt = null;
    try {
        conn = UserDatabase.getConnection();
        //make a statement
        stmt = conn
                .prepareStatement("INSERT INTO APPUSER (username, password, enabled) VALUES (?, ?, 'enabled')");
        stmt.setString(1, username);
        stmt.setString(2, hashedPassword);
        log.debug("Add user: {}", stmt.execute());
        //add role
        stmt = conn.prepareStatement("INSERT INTO APPROLE (username, authority) VALUES (?, 'ROLE_SUPERVISOR')");
        stmt.setString(1, username);
        log.debug("Add role: {}", stmt.execute());
        //
        result = true;
    } catch (Exception e) {
        log.error("Error connecting to db", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            UserDatabase.recycle(conn);
        }
    }
    return result;
}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectUtils.java

/**
 * Rejects a project for the given user//from w  w w .  jav  a 2s .  c  o m
 *
 * @param db        Description of the Parameter
 * @param projectId Description of the Parameter
 * @param userId    Description of the Parameter
 * @throws SQLException Description of the Exception
 */
public static void reject(Connection db, int projectId, int userId) throws SQLException {
    // Remove the user...
    PreparedStatement pst = db.prepareStatement(
            "DELETE FROM project_team " + "WHERE project_id = ? " + "AND user_id = ? " + "AND status = ? ");
    pst.setInt(1, projectId);
    pst.setInt(2, userId);
    pst.setInt(3, TeamMember.STATUS_PENDING);
    pst.execute();
    pst.close();
    CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, projectId);
}

From source file:com.winit.vms.base.db.mybatis.support.SQLHelp.java

/**
 * // w w w  .  j  a  v  a2s. co  m
 *
 * @param sql             SQL?
 * @param mappedStatement mapped
 * @param parameterObject ?
 * @param boundSql        boundSql
 * @param dialect         database dialect
 * @return 
 * @throws java.sql.SQLException sql
 */
public static int getCount(final String sql, final MappedStatement mappedStatement,
        final Object parameterObject, final BoundSql boundSql, Dialect dialect) throws SQLException {
    final String count_sql = dialect.getCountString(sql);
    logger.debug("Total count SQL [{}] ", count_sql);
    logger.debug("Total count Parameters: {} ", parameterObject);

    DataSource dataSource = mappedStatement.getConfiguration().getEnvironment().getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    PreparedStatement countStmt = null;
    ResultSet rs = null;
    try {
        countStmt = connection.prepareStatement(count_sql);
        //Page SQLCount SQL???boundSql
        DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement, parameterObject,
                boundSql);
        handler.setParameters(countStmt);

        rs = countStmt.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        logger.debug("Total count: {}", count);
        return count;
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } finally {
            try {
                if (countStmt != null) {
                    countStmt.close();
                }
            } finally {
                DataSourceUtils.releaseConnection(connection, dataSource);
            }
        }
    }
}