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.example.spring.jdbc.template.CustomerDao.java

public Boolean saveCustomereByPreparedStatement(final Customer e) {
    String query = "insert into customer values(?,?,?)";
    return jdbcTemplate.execute(query, new PreparedStatementCallback<Boolean>() {
        @Override/*from  ww w.j av a 2  s. c  o m*/
        public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {

            ps.setString(1, e.getCutomerId());
            ps.setString(2, e.getName());
            ps.setString(3, e.getEmail());

            return ps.execute();

        }
    });

}

From source file:com.keybox.manage.db.UserDB.java

/**
 * inserts new user//  w w  w .j a  va2  s .c  o  m
 * 
 * @param con DB connection 
 * @param user user object
 */
public static Long insertUser(Connection con, User user) {

    Long userId = null;

    try {
        PreparedStatement stmt = con.prepareStatement(
                "insert into users (first_nm, last_nm, email, username, auth_type, user_type, password, salt) values (?,?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, user.getFirstNm());
        stmt.setString(2, user.getLastNm());
        stmt.setString(3, user.getEmail());
        stmt.setString(4, user.getUsername());
        stmt.setString(5, user.getAuthType());
        stmt.setString(6, user.getUserType());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String salt = EncryptionUtil.generateSalt();
            stmt.setString(7, EncryptionUtil.hash(user.getPassword() + salt));
            stmt.setString(8, salt);
        } else {
            stmt.setString(7, null);
            stmt.setString(8, null);
        }
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs != null && rs.next()) {
            userId = rs.getLong(1);
        }
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

    return userId;

}

From source file:com.reydentx.core.client.MySQLClient.java

public int executeMultiQuery(List<String> listQuery) {
    Connection conn = borrowClient();
    if (conn == null) {
        return (-1);
    }//from   w  w w  .  ja  v a 2 s.com
    try {
        conn.setAutoCommit(false);
        for (String query : listQuery) {
            PreparedStatement ps = conn.prepareStatement(query);
            ps.execute();
        }
        conn.commit();
        returnObject(conn);
    } catch (SQLException sqlEx) {
        try {
            _logger.error("Rollback traction because ex:" + sqlEx.getMessage(), sqlEx);
            conn.rollback(); // must be innoDB
        } catch (SQLException sqlExRollback) {
            _logger.error(sqlExRollback.getMessage(), sqlExRollback);
        }
    } catch (Exception ex) {
        _logger.error(ex.getMessage(), ex);
        invalidClient(conn);
        return (-1);
    } finally {
        try {
            conn.setAutoCommit(true);
        } catch (Exception ex) {
            _logger.error(ex.getMessage(), ex);
        }
    }
    return 0;
}

From source file:de.klemp.middleware.controller.Controller.java

private static void deleteDevices() {
    createDBConnection();//from   ww w  .  ja v  a  2 s .  com
    PreparedStatement stp;
    try {
        stp = conn.prepareStatement("delete from \"InputDevices\";");
        stp.execute();
        stp = conn.prepareStatement("delete from \"OutputDevices\";");
        stp.execute();
        stp = conn.prepareStatement(
                "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' and table_name!='InputDevices'and table_name!='OutputDevices' and table_name!='Classes'and table_name!='Data'and table_name!='Controller'");
        ResultSet result = stp.executeQuery();
        while (result.next()) {
            String table = result.getString(1);
            stp = conn.prepareStatement("delete from \"" + table + "\";");
            stp.execute();
        }
    } catch (SQLException e) {
        logger.error("SQL Exception in deleteDevices()", e);
    }
    closeDBConnection();
    deviceActive.clear();
}

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

public static void saveData() {
    java.sql.Connection con = null;
    try {/* w  w  w . j  ava2  s.c  o m*/
        con = L2DatabaseFactory.getInstance().getConnection();
        PreparedStatement statement;
        statement = con.prepareStatement("Delete from tvt");
        statement.execute();
        statement.close();
        statement = con.prepareStatement(
                "INSERT INTO tvt (eventName, eventDesc, joiningLocation, minlvl, maxlvl, npcId, npcX, npcY, npcZ, npcHeading, rewardId, rewardAmount, teamsCount, joinTime, eventTime, minPlayers, maxPlayers) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        statement.setString(1, _eventName);
        statement.setString(2, _eventDesc);
        statement.setString(3, _joiningLocationName);
        statement.setInt(4, _minlvl);
        statement.setInt(5, _maxlvl);
        statement.setInt(6, _npcId);
        statement.setInt(7, _npcX);
        statement.setInt(8, _npcY);
        statement.setInt(9, _npcZ);
        statement.setInt(10, _npcHeading);
        statement.setInt(11, _rewardId);
        statement.setInt(12, _rewardAmount);
        statement.setInt(13, _teams.size());
        statement.setInt(14, _joinTime);
        statement.setInt(15, _eventTime);
        statement.setInt(16, _minPlayers);
        statement.setInt(17, _maxPlayers);
        statement.execute();
        statement.close();
        statement = con.prepareStatement("Delete from tvt_teams");
        statement.execute();
        statement.close();
        for (String teamName : _teams) {
            int index = _teams.indexOf(teamName);
            if (index == -1)
                return;
            statement = con.prepareStatement(
                    "INSERT INTO tvt_teams (teamId ,teamName, teamX, teamY, teamZ, teamColor) VALUES (?, ?, ?, ?, ?, ?)");
            statement.setInt(1, index);
            statement.setString(2, teamName);
            statement.setInt(3, _teamsX.get(index));
            statement.setInt(4, _teamsY.get(index));
            statement.setInt(5, _teamsZ.get(index));
            statement.setInt(6, _teamColors.get(index));
            statement.execute();
            statement.close();
        }
    } catch (Exception e) {
        _log.error("Exception: TvT.saveData(): " + e.getMessage());
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:azkaban.jobtype.ReportalTeradataRunner.java

@Override
protected void runReportal() throws Exception {
    System.out.println("Reportal Teradata: Setting up Teradata");
    List<Exception> exceptions = new ArrayList<Exception>();

    Class.forName("com.teradata.jdbc.TeraDriver");
    String connectionString = props.getString("reportal.teradata.connection.string", null);

    String user = props.getString("reportal.teradata.username", null);
    String pass = props.getString("reportal.teradata.password", null);
    if (user == null) {
        System.out.println("Reportal Teradata: Configuration incomplete");
        throw new RuntimeException("The reportal.teradata.username variable was not defined.");
    }//from  w  ww  .j  av  a2s .  co m
    if (pass == null) {
        System.out.println("Reportal Teradata: Configuration incomplete");
        throw new RuntimeException("The reportal.teradata.password variable was not defined.");
    }

    DataSource teraDataSource = new TeradataDataSource(connectionString, user, pass);
    Connection conn = teraDataSource.getConnection();

    String sqlQueries[] = cleanAndGetQueries(jobQuery, proxyUser);

    int numQueries = sqlQueries.length;

    for (int i = 0; i < numQueries; i++) {
        try {
            String queryLine = sqlQueries[i];

            // Only store results from the last statement
            if (i == numQueries - 1) {
                PreparedStatement stmt = prepareStatement(conn, queryLine);
                stmt.execute();
                ResultSet rs = stmt.getResultSet();
                outputQueryResult(rs, outputStream);
                stmt.close();
            } else {
                try {
                    PreparedStatement stmt = prepareStatement(conn, queryLine);
                    stmt.execute();
                    stmt.close();
                } catch (NullPointerException e) {
                    // An empty query (or comment) throws a NPE in JDBC. Yay!
                    System.err.println(
                            "Caught NPE in execute call because report has a NOOP query: " + queryLine);
                }
            }
        } catch (Exception e) {
            // Catch and continue. Delay exception throwing until we've run all queries in this task.
            System.out.println("Reportal Teradata: SQL query failed. " + e.getMessage());
            e.printStackTrace();
            exceptions.add(e);
        }
    }

    if (exceptions.size() > 0) {
        throw new CompositeException(exceptions);
    }

    System.out.println("Reportal Teradata: Ended successfully");
}

From source file:com.haulmont.cuba.core.app.UniqueNumbers.java

protected Object executeScript(String domain, String sqlScript) {
    EntityManager em = persistence.getEntityManager(getDataStore(domain));
    StrTokenizer tokenizer = new StrTokenizer(sqlScript, SequenceSupport.SQL_DELIMITER);
    Object value = null;//from ww w .  j  a  v  a2 s  .  co  m
    Connection connection = em.getConnection();
    while (tokenizer.hasNext()) {
        String sql = tokenizer.nextToken();
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                if (statement.execute()) {
                    ResultSet rs = statement.getResultSet();
                    if (rs.next())
                        value = rs.getLong(1);
                }
            } finally {
                DbUtils.closeQuietly(statement);
            }
        } catch (SQLException e) {
            throw new IllegalStateException("Error executing SQL for getting next number", e);
        }
    }
    return value;
}

From source file:com.yahoo.sql4d.indexeragent.sql.DBAccessor.java

/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params/*from w w w.  ja v a2s  . c  om*/
 * @param query 
 * @return  
 */
public boolean execute(Map<String, String> params, String query) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Tuple2<DataSource, Connection> conn = null;
    try {
        conn = getConnection();
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
        jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
            @Override
            public Void doInPreparedStatement(PreparedStatement ps) {
                try {
                    result.set(ps.execute());
                } catch (SQLException e) {
                    result.set(false);
                }
                return null;
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}

From source file:com.l2jfree.gameserver.util.OfflineTradeManager.java

private void cleanTables() {
    Connection con = null;/*from  w ww . ja v  a2s.  com*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement("TRUNCATE TABLE offline_traders");
        statement.execute();
        statement.close();
        statement = con.prepareStatement("TRUNCATE TABLE offline_traders_items");
        statement.execute();
        statement.close();
    } catch (Exception e) {
        _log.warn("OfflineTradeManager: Could not clear table: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:de.iritgo.aktario.jdbc.DeleteUser.java

/**
 * Perform the command.//from w ww .  j  a  v a 2 s.  c o m
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "DeleteUser", "Missing unique id for the user to delete");

        return;
    }

    UserRegistry userRegistry = Server.instance().getUserRegistry();
    long userId = ((Long) properties.get("id")).longValue();
    User user = userRegistry.getUser(userId);

    if (user == null) {
        Log.logError("persist", "DeleteUser", "Unable to find user with id " + userId);

        return;
    }

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("delete from IritgoUser where id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        Log.logVerbose("persist", "DeleteUser", "DELETE USER " + userId);
    } catch (SQLException x) {
        Log.logError("persist", "DeleteUser", "Error while storing user with id " + userId + ": " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}