Example usage for java.sql PreparedStatement setString

List of usage examples for java.sql PreparedStatement setString

Introduction

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

Prototype

void setString(int parameterIndex, String x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java String value.

Usage

From source file:index.IncrementIndex.java

public static ResultSet getResult(String storeId, String sqlPath, String defaultPath) throws Exception {
    // ??//www  .j a va2s  . com
    config.load(new FileInputStream(sqlPath));
    // 
    String jdbcDriverClassName = config.getProperty("jdbcDriverClassName");
    String jdbcUrl = "jdbc:db2://";
    if (jdbcDriverClassName.contains("db2")) {
        jdbcUrl = "jdbc:db2://";
    } else if (jdbcDriverClassName.contains("mysql")) {
        jdbcUrl = "jdbc:mysql://";
    } else if (jdbcDriverClassName.contains("sqlserver")) {
        jdbcUrl = "jdbc:sqlserver://";
    } else if (jdbcDriverClassName.contains("sourceforge")) {
        jdbcUrl = "jdbc:jtds:sqlserver://";
    } else if (jdbcDriverClassName.contains("oracle")) {
        jdbcUrl = "jdbc:oracle:thin:@";
    }
    // url
    jdbcUrl = jdbcUrl + config.getProperty("iampDBIp") + ":" + config.getProperty("iampDBPort") + "/"
            + config.getProperty("iampDBName");
    String jdbcUsername = config.getProperty("iampDBUserName");
    String jdbcPassword = config.getProperty("iampDBPassword");
    // ?
    Class.forName(jdbcDriverClassName).newInstance();
    Connection conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
    // ???
    config.load(new FileInputStream(defaultPath));
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String sql;
    if ("0".equals(storeId)) {
        sql = config.getProperty("nullSql");
        stmt = conn.prepareStatement(sql);
        rs = stmt.executeQuery();
    } else {
        sql = config.getProperty("entitySql");

        System.out.print("sql=" + sql);
        stmt = conn.prepareStatement(sql);
        stmt.setString(1, storeId);
        // 
        rs = stmt.executeQuery();
    }

    return rs;
}

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

public static Boolean updateUploadData(Video data, VideoMetadata metadata, int id)
        throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "UPDATE `uploads` SET `data`=?,`metadata`=? WHERE `id`=?";
    prest = c.prepareStatement(sql);//  www .  j  a  v  a 2  s  .c  o  m
    prest.setString(1, mapper.writeValueAsString(data));
    prest.setString(2, mapper.writeValueAsString(metadata));
    prest.setInt(3, id);
    boolean res = prest.execute();
    prest.close();
    return res;
}

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

/**
 * Update the "last accessed" information of a user.
 * @param userName the user name to update.
 * @param accessData semicolon-delimited string of values.
 * @return true if the last access information for the user was updated successfully, false otherwise.
 *//*from  w  ww. ja v a2s  .c  o m*/
public static boolean updateLastProject(String userName, String accessData) {
    if (!MetaDbHelper.userExists(userName))
        return false;

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

            updateUser.setString(1, accessData);
            updateUser.setString(2, userName);
            updateUser.executeUpdate();

            updateUser.close();
            conn.close(); // Close statement and connection

            return true;

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

        }
    }
    return false;

}

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

/**
 * Get a user's data.//from  www .j  av a2s.co  m
 * 
 * @param userName The username of the desired user.    
 * @return a User object with username, password and type for the requested user.
 * 
 */
public static User getUserData(String userName) {
    User requestedUser = null; // initialize return object

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            if (!MetaDbHelper.userExists(userName)) // If user doesn't exist
                return new User("", "", "", "", 0, ""); //Return a dummy user
            PreparedStatement getUserQuery = conn.prepareStatement(GET_USER_DATA);

            getUserQuery.setString(1, userName); // set parameter
            ResultSet userData = getUserQuery.executeQuery();

            if (userData != null) // The query result was not null
            {
                userData.next();
                // Get parameters
                String password = userData.getString(Global.USER_PASSWORD);
                String type = userData.getString(Global.USER_TYPE);
                String authType = userData.getString(Global.USER_AUTH_TYPE);
                long last_login = userData.getLong(Global.USER_LAST_LOGIN);
                String lastProj = userData.getString(Global.USER_LAST_ACCESS);
                requestedUser = new User(userName, password, type, authType, last_login, lastProj);

            }

            getUserQuery.close();
            userData.close();

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

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

public static Boolean updateUpload(int account, File file, Video data, String enddir, VideoMetadata metadata,
        int id) throws SQLException, IOException {
    PreparedStatement prest = null;
    String sql = "UPDATE `uploads` SET `account`=?, `file`=?, `lenght`=?, `enddir`=? WHERE `id`=?";
    prest = c.prepareStatement(sql);//from  w ww.j  a v a2 s.  co  m
    prest.setInt(1, account);
    prest.setString(2, file.getAbsolutePath());
    prest.setLong(3, file.length());
    prest.setString(4, enddir);
    prest.setInt(5, id);
    boolean res = prest.execute();
    prest.close();
    boolean upd = updateUploadData(data, metadata, id);
    return res && upd;
}

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

public static void insertPlaylist(Item item, int account) throws SQLException, IOException {
    PreparedStatement prest = null;
    String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`,`shown`) "
            + "VALUES (?,?,?,?,1)";
    prest = c.prepareStatement(sql);/*from  ww  w .  java2  s .  c  om*/
    prest.setString(1, item.snippet.title);
    prest.setString(2, item.id);
    URL url = new URL(item.snippet.thumbnails.default__.url);
    InputStream is = null;
    is = url.openStream();
    byte[] imageBytes = IOUtils.toByteArray(is);
    prest.setBytes(3, imageBytes);
    prest.setInt(4, account);
    prest.execute();
    prest.close();
}

From source file:com.novartis.opensource.yada.util.YADAUtils.java

/**
 * One-liner execution of a sql statement, returning an SQL {@link java.sql.ResultSet}.
 * <strong>Note: This method opens a db connection but DOES NOT CLOSE IT. 
 * Use the static method {@link ConnectionFactory#releaseResources(ResultSet)} to close it from 
 * the calling method</strong>/*from  ww w . ja  v a 2  s. c o  m*/
 * @param sql the query to execute
 * @param params the data values to map to query columns
 * @return a {@link java.sql.ResultSet} object containing the result of the query
 * @throws YADAConnectionException when the datasource is inaccessible
 * @throws YADASQLException when the JDBC configuration or execution fails
 */
public static ResultSet executePreparedStatement(String sql, Object[] params)
        throws YADAConnectionException, YADASQLException {
    ResultSet rs = null;
    try {
        Connection c = ConnectionFactory.getConnectionFactory().getConnection(ConnectionFactory.YADA_APP);
        PreparedStatement p = c.prepareStatement(sql);
        for (int i = 1; i <= params.length; i++) {
            Object param = params[i - 1];
            if (param instanceof String) {
                p.setString(i, (String) param);
            } else if (param instanceof Date) {
                p.setDate(i, (Date) param);
            } else if (param instanceof Integer) {
                p.setInt(i, ((Integer) param).intValue());
            } else if (param instanceof Float) {
                p.setFloat(i, ((Float) param).floatValue());
            }
        }
        rs = p.executeQuery();
    } catch (SQLException e) {
        throw new YADASQLException(e.getMessage(), e);
    }
    return rs;
}

From source file:com.useekm.indexing.postgis.IndexedStatement.java

/**
 * Search for a statements with a given text predicate. For testing purposes
 * only.// w ww  . jav a 2 s .c o m
 * 
 * @param vectorConfig
 *            Name of the configuration to use for building the query.
 * @param query
 *            The search query, e.g. "apples & oranges".
 * @return An closeable iteration to the resulting {@link IndexedStatement}
 *         s.
 */
static CloseableIterator<IndexedStatement> search(Connection conn, String table, String vectorConfig,
        String query) throws SQLException, IndexException {
    Validate.notEmpty(query);
    validateConfig(vectorConfig);
    StringBuffer sql = new StringBuffer(MAX_SELECT_LEN).append(SELECT + table).append(WHERE);
    sql.append(OBJECT_TS_VECTOR);
    sql.append("@@to_tsquery('").append(vectorConfig).append("',?)");
    PreparedStatement stat = conn.prepareStatement(sql.toString());
    StatementIterator result = null;
    try {
        stat.setString(1, query);
        result = new StatementIterator(stat);
    } finally {
        if (result == null) // else StatementIterator should close the stat
            stat.close();
    }
    return result;
}

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

public static Boolean updateTemplate(int id, Template template) throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "UPDATE `templates` SET `data`=? WHERE `id`=?";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setString(1, mapper.writeValueAsString(template));
    prest.setInt(2, id);//ww w  . ja  va  2 s.  c  o  m
    boolean res = prest.execute();
    prest.close();
    return res;
}

From source file:com.ec2box.manage.db.UserThemeDB.java

/**
 * saves user theme/*from   w w  w.  java 2s  . c om*/
 * 
 * @param userId object
 */
public static void saveTheme(Long userId, UserSettings theme) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement("delete from user_theme where user_id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        DBUtils.closeStmt(stmt);

        if (StringUtils.isNotEmpty(theme.getPlane()) || StringUtils.isNotEmpty(theme.getTheme())) {

            stmt = con.prepareStatement(
                    "insert into user_theme(user_id, bg, fg, d1, d2, d3, d4, d5, d6, d7, d8, b1, b2, b3, b4, b5, b6, b7, b8) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            stmt.setLong(1, userId);
            stmt.setString(2, theme.getBg());
            stmt.setString(3, theme.getFg());
            //if contains all 16 theme colors insert
            if (theme.getColors() != null && theme.getColors().length == 16) {
                for (int i = 0; i < 16; i++) {
                    stmt.setString(i + 4, theme.getColors()[i]);
                }
                //else set to null
            } else {
                for (int i = 0; i < 16; i++) {
                    stmt.setString(i + 4, null);
                }
            }
            stmt.execute();
            DBUtils.closeStmt(stmt);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DBUtils.closeConn(con);
    }

}