Example usage for java.sql PreparedStatement execute

List of usage examples for java.sql PreparedStatement execute

Introduction

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

Prototype

boolean execute() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

Usage

From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java

private long savePhone(Connection conn, Phone phone) {
    String sql = "insert into t_phone(f_number, f_phonetype) values(?, ?)";
    long id = -1;
    try {/*from  www .j  a  v a2 s .c  o m*/
        // ?,?getGeneratedKeys
        PreparedStatement preState = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
        preState.setString(1, phone.getNumber());
        preState.setInt(2, phone.getPhoneType());
        preState.execute();
        id = generateId(preState);
        if (-1 != id) {
            phone.setId(id);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return id;
}

From source file:dao.MaterialDaoImplem.java

@Override
public boolean updateMaterial(Material material) {
    try (Connection connection = dataSource.getConnection()) {
        String query = ("update Material m "
                + "set m.name=?, m.weight=?, m.manufacturer=?,m.cost=?,m.quantity=? WHERE m.id_material=?");
        PreparedStatement stat = connection.prepareStatement(query);
        stat.setString(1, material.getName());
        stat.setInt(2, material.getWeight());
        stat.setString(3, material.getManufacturer());
        stat.setInt(4, material.getCost());
        stat.setInt(5, material.getQuantity());
        stat.setInt(6, material.getId_material());
        stat.execute();
        return true;
    } catch (Exception e) {
        throw new RuntimeException("Error:updateMaterial", e);
    }/*from   w  ww .  j  a va  2s .com*/
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertFromSubselectWithCast() throws Exception {
    Connection conn = methodWatcher.getOrCreateConnection();
    PreparedStatement ps = conn.prepareStatement("insert into t7 values ('Jackson')");
    ps.execute();
    String sql = "insert into T6\n" + "SELECT \n" + "instr(name, 'ack') as i\n" + "FROM \n" + "(SELECT \n"
            + "name\t\n" + "FROM T7 \n" + ") T1";

    // Make sure insert works with a subselect and instr
    ps = conn.prepareStatement(sql);//from  ww w . j a v  a2s  . c  o m
    int count = ps.executeUpdate();
    Assert.assertTrue(count == 1);

    // verify results
    ps = conn.prepareStatement("select * from t6");
    ResultSet rs = ps.executeQuery();
    Assert.assertTrue(rs.next());
    Assert.assertTrue(rs.getInt(1) == 2);
}

From source file:net.sf.l2j.gameserver.instancemanager.CoupleManager.java

public void deleteCouple(int coupleId) {
    int index = getCoupleIndex(coupleId);
    Couple couple = getCouples().get(index);
    if (couple != null) {
        L2PcInstance player1 = (L2PcInstance) L2World.getInstance().findObject(couple.getPlayer1Id());
        L2PcInstance player2 = (L2PcInstance) L2World.getInstance().findObject(couple.getPlayer2Id());
        L2ItemInstance item = null;/*from  w ww.  j  a  v a2 s .c o  m*/
        if (player1 != null) {
            player1.setPartnerId(0);
            player1.setMaried(false);
            player1.setCoupleId(0);
            item = player1.getInventory().getItemByItemId(9140);
            if (player1.isOnline() == 1 && item != null) {
                player1.destroyItem("Removing Cupids Bow", item, player1, true);
                player1.getInventory().updateDatabase();
            }
            if (player1.isOnline() == 0 && item != null) {
                Integer PlayerId = player1.getObjectId();
                Integer ItemId = 9140;
                java.sql.Connection con = null;
                try {
                    con = L2DatabaseFactory.getInstance().getConnection();
                    PreparedStatement statement = con
                            .prepareStatement("delete from items where owner_id = ? and item_id = ?");
                    statement.setInt(1, PlayerId);
                    statement.setInt(2, ItemId);
                    statement.execute();
                    statement.close();
                } catch (Exception e) {
                } finally {
                    try {
                        con.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        if (player2 != null) {
            player2.setPartnerId(0);
            player2.setMaried(false);
            player2.setCoupleId(0);
            item = player2.getInventory().getItemByItemId(9140);
            if (player2.isOnline() == 1 && item != null) {
                player2.destroyItem("Removing Cupids Bow", item, player2, true);
                player2.getInventory().updateDatabase();
            }
            if (player2.isOnline() == 0 && item != null) {
                Integer Player2Id = player2.getObjectId();
                Integer Item2Id = 9140;
                java.sql.Connection con = null;
                try {
                    con = L2DatabaseFactory.getInstance().getConnection();
                    PreparedStatement statement = con
                            .prepareStatement("delete from items where owner_id = ? and item_id = ?");
                    statement.setInt(1, Player2Id);
                    statement.setInt(2, Item2Id);
                    statement.execute();
                    statement.close();
                } catch (Exception e) {
                } finally {
                    try {
                        con.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        couple.divorce();
        getCouples().remove(index);
    }
}

From source file:net.mindengine.oculus.frontend.service.project.build.JdbcBuildDAO.java

@Override
public long createBuild(Build build) throws Exception {
    String sql = "insert into builds (name, description, date, project_id) values (?,?,?,?)";
    PreparedStatement ps = getConnection().prepareStatement(sql);
    ps.setString(1, build.getName());//from  w w w  .  jav a  2  s . c om
    ps.setString(2, build.getDescription());
    ps.setTimestamp(3, new Timestamp(build.getDate().getTime()));
    ps.setLong(4, build.getProjectId());

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return 0;
}

From source file:edu.umd.cs.psl.database.rdbms.RDBMSDataStoreMetadata.java

protected String getValue(String mdTableName, String space, String type, String key) {
    try {//from  ww w .  jav a2s  .  co  m
        PreparedStatement stmt = conn.prepareStatement(
                "SELECT value from " + mdTableName + " WHERE namespace = ? AND keytype = ? AND key = ?");
        stmt.setString(1, space);
        stmt.setString(2, type);
        stmt.setString(3, key);
        stmt.execute();
        ResultSet rs = stmt.getResultSet();
        if (rs.next()) {
            return rs.getString(1);
        }
    } catch (Exception e) {
        log.info("Error getting value for key " + key + " - " + e.getMessage());
        return null;
    }
    return null;
}

From source file:edu.education.ucsb.muster.MusterServlet.java

private String getOutputAsJson(String database, String query, long limit) throws SQLException {

    // The output string
    StringBuffer out = new StringBuffer();

    // Cache StringBuffer length as needed
    int len;/*from   w ww . jav  a2  s . com*/

    // Database operations
    DatabaseDefinition db = conf.getDatabase(database);

    // //register the driver
    registerDriver(db.driver, db.url);

    // // Connect to the database
    Connection connection = DriverManager.getConnection(db.url, db.username, db.password);

    // // Perform the query
    PreparedStatement statement = connection.prepareStatement(query);
    statement.execute();
    ResultSet results = statement.getResultSet();

    // Get and write the column names
    ResultSetMetaData meta = results.getMetaData();
    int columnCount = meta.getColumnCount();
    LinkedList<String> columns = new LinkedList<String>();
    for (int i = 1; i < columnCount + 1; i++) {
        // We're only dealing with JSON, so the column names should be
        // JavaScript-friendly.
        columns.add(StringEscapeUtils.escapeJavaScript(meta.getColumnName(i)));
    }
    out.append("{\n  \"columns\" : [ ");

    // Add column names in JSON format
    for (String column : columns) {
        out.append('"' + column + "\", ");
    }

    // remove the trailing ", " and add a line break and close the array
    len = out.length();
    out.delete(len - 2, len);
    out.append(" ],\n");

    // Add column values
    out.append("  \"results\" : [ \n");

    for (int i = 0; i < limit && results.next(); i++) {
        out.append(rowAsJson(results, columns));
    }

    // remove the trailing ", "
    len = out.length();
    out.delete(len - 2, len);
    out.append("\n  ]\n");
    out.append("}");

    return out.toString();
}

From source file:net.sf.l2j.gameserver.model.entity.Couple.java

public void marry() {
    java.sql.Connection con = null;
    try {/*w  w w .  j a va2  s. co m*/
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement;
        statement = con.prepareStatement("UPDATE couples set maried = ?, weddingDate = ? where id = ?");
        statement.setBoolean(1, true);
        _weddingDate = Calendar.getInstance();
        statement.setLong(2, _weddingDate.getTimeInMillis());
        statement.setInt(3, _Id);
        statement.execute();
        statement.close();
        _maried = true;
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:Crawler.CrawlerClass.java

public void InsertToContentDb(DBConnection Conn, String url, String Description, String Title, String Content,
        String Extension) throws SQLException, IOException {

    String sql = "select * from contentdb where URL = '" + url + "'";
    ResultSet rs = Conn.executeStatement(sql);

    if (!rs.next()) {
        //store the URL to database to avoid parsing again
        //sql = "INSERT INTO  `contentdb` " + "(`URL`, ) VALUES " + "(?);";
        sql = "INSERT INTO `contentdb`(`URL`, `Description`, `Title`, `Content_description`, `Page_extension`) "
                + "VALUES(?,?,?,?,?);";
        PreparedStatement stmt = Conn.conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, url);/*from   w  ww.  j a va 2s  .  c o  m*/
        stmt.setString(2, Description);
        stmt.setString(3, Title);
        stmt.setString(4, Content);
        stmt.setString(5, Extension);
        stmt.execute();
    }
}

From source file:com.qcloud.component.snaker.access.mybatis.MybatisAccess.java

/**
 * JDBC?BLOB/*  w  w w .ja va  2 s  . c  o  m*/
 */
public void saveProcess(Process process) {

    super.saveProcess(process);
    SqlSession sqlSession = getSession();
    if (process.getBytes() != null) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = sqlSession.getConnection();
            pstmt = conn.prepareStatement(PROCESS_UPDATE_BLOB);
            pstmt.setBytes(1, process.getBytes());
            pstmt.setString(2, process.getId());
            pstmt.execute();
        } catch (Exception e) {
            throw new SnakerException(e.getMessage(), e.getCause());
        } finally {
            try {
                JdbcHelper.close(pstmt);
                SqlSessionUtils.closeSqlSession(sqlSession, getSqlSessionFactory());
            } catch (SQLException e) {
                throw new SnakerException(e.getMessage(), e.getCause());
            }
        }
    }
}