List of usage examples for java.sql PreparedStatement execute
boolean execute() throws SQLException;
PreparedStatement
object, which may be any kind of SQL statement. From source file:com.firewallid.util.FISQL.java
public static void updateRowInsertIfNotExist(Connection conn, String tableName, Map<String, String> updateConditions, Map<String, String> fields) throws SQLException { /* Query *///from w ww . j a v a2 s . c om String query = "SELECT " + Joiner.on(", ").join(updateConditions.keySet()) + " FROM " + tableName + " WHERE " + Joiner.on(" = ? AND ").join(updateConditions.keySet()) + " = ?"; /* Execute */ PreparedStatement pst = conn.prepareStatement(query); int i = 1; for (String value : updateConditions.values()) { pst.setString(i, value); i++; } ResultSet executeQuery = pst.executeQuery(); if (executeQuery.next()) { /* Update */ query = "UPDATE " + tableName + " SET " + Joiner.on(" = ?, ").join(fields.keySet()) + " = ? WHERE " + Joiner.on(" = ? AND ").join(updateConditions.keySet()) + " = ?"; pst = conn.prepareStatement(query); i = 1; for (String value : fields.values()) { pst.setString(i, value); i++; } for (String value : updateConditions.values()) { pst.setString(i, value); i++; } pst.executeUpdate(); return; } /* Row is not exists. Insert */ query = "INSERT INTO " + tableName + " (" + Joiner.on(", ").join(fields.keySet()) + ", " + Joiner.on(", ").join(updateConditions.keySet()) + ") VALUES (" + StringUtils.repeat("?, ", fields.size() + updateConditions.size() - 1) + "?)"; pst = conn.prepareStatement(query); i = 1; for (String value : fields.values()) { pst.setString(i, value); i++; } for (String value : updateConditions.values()) { pst.setString(i, value); i++; } pst.execute(); }
From source file:com.l2jfree.gameserver.gameobjects.skills.PlayerSkills.java
public void storeSkill(L2Skill skill, int classIndex) { if (skill == null) return;/* w ww . j a v a 2s . com*/ final SkillMap map = getSkillMap(classIndex); final Integer oldLevel = map.put(skill); checkStoredSkill(skill, classIndex); if (oldLevel != null && oldLevel.intValue() == skill.getLevel()) return; Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(); if (oldLevel != null) { PreparedStatement statement = con.prepareStatement( "UPDATE character_skills SET skill_level=? WHERE skill_id=? AND charId=? AND class_index=?"); statement.setInt(1, skill.getLevel()); statement.setInt(2, skill.getId()); statement.setInt(3, getOwner().getObjectId()); statement.setInt(4, classIndex); statement.execute(); statement.close(); } else { PreparedStatement statement = con.prepareStatement( "INSERT INTO character_skills (charId,skill_id,skill_level,class_index) VALUES (?,?,?,?)"); statement.setInt(1, getOwner().getObjectId()); statement.setInt(2, skill.getId()); statement.setInt(3, skill.getLevel()); statement.setInt(4, classIndex); statement.execute(); statement.close(); } } catch (Exception e) { _log.warn("", e); } finally { L2DatabaseFactory.close(con); } }
From source file:com.sf.springsecurityregistration1.core.repository.UserRepositoryJPA.java
private <T> void persistWithJDBC(T dto) throws SQLException { String table = dto.getClass().getAnnotation(javax.persistence.Table.class).name(); // System.out.println("table " + table); final String ROLE = "role"; boolean isRole = table.toLowerCase().contains(ROLE); final String INSERT_USER = "INSERT INTO " + table + " (username, " + (isRole ? ROLE : "password") + ") VALUES (?, ?)"; Connection connection = null; try {/*from www.j av a 2 s .co m*/ Properties connectionProps = new Properties(); connectionProps.put("user", dbUsername); connectionProps.put("password", dbPassword); connection = DriverManager.getConnection(dbURL, connectionProps); connection.setAutoCommit(false); PreparedStatement insertUser = connection.prepareStatement(INSERT_USER); if (isRole) { UserRoles role = (UserRoles) dto; insertUser.setString(1, role.getUsername()); insertUser.setString(2, role.getRole()); } else { Users user = (Users) dto; insertUser.setString(1, user.getUsername()); insertUser.setString(2, user.getPassword()); } insertUser.execute(); connection.commit(); } finally { if (connection != null) { connection.close(); } } }
From source file:com.splicemachine.derby.test.framework.SpliceUserWatcher.java
public void dropUser(String userName) { Connection connection = null; PreparedStatement statement = null; try {/* www .j a v a2 s.c om*/ connection = SpliceNetConnection.getConnection(); statement = connection.prepareStatement("select username from sys.sysusers where username = ?"); statement.setString(1, userName.toUpperCase()); ResultSet rs = statement.executeQuery(); if (rs.next()) { statement = connection.prepareStatement("call syscs_util.syscs_drop_user(?)"); statement.setString(1, userName); statement.execute(); } } catch (Exception e) { LOG.error("error Creating " + e.getMessage()); e.printStackTrace(); throw new RuntimeException(e); } finally { DbUtils.closeQuietly(statement); DbUtils.commitAndCloseQuietly(connection); } }
From source file:net.mindengine.oculus.frontend.service.customization.JdbcCustomizationDAO.java
@Override public long saveUnitCustomizationValue(UnitCustomizationValue unitCustomizationValue) throws Exception { UnitCustomizationValue value = null; if (unitCustomizationValue.getId() == null || unitCustomizationValue.getId() < 1) { value = getUnitCustomizationValue(unitCustomizationValue.getCustomizationId(), unitCustomizationValue.getUnitId()); } else// www . j a v a 2 s. co m value = unitCustomizationValue; if (value == null) { PreparedStatement ps = getConnection().prepareStatement( "insert into unit_customization_values (unit_id, customization_id, value) values (?,?,?)"); ps.setLong(1, unitCustomizationValue.getUnitId()); ps.setLong(2, unitCustomizationValue.getCustomizationId()); ps.setString(3, unitCustomizationValue.getValue()); logger.info(ps); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { return rs.getLong(1); } } else { update("update unit_customization_values set value = :value where id = :id", "value", unitCustomizationValue.getValue(), "id", value.getId()); return value.getId(); } return 0; }
From source file:dk.netarkivet.harvester.datamodel.MySQLSpecifics.java
/** Get a temporary table for short-time use. The table should be * disposed of with dropTemporaryTable. The table has two columns * domain_name varchar(Constants.MAX_NAME_SIZE) * config_name varchar(Constants.MAX_NAME_SIZE) * * @param c The DB connection to use.//ww w . ja va2s .c o m * @throws SQLException if there is a problem getting the table. * @return The name of the created table */ public String getJobConfigsTmpTable(Connection c) throws SQLException { ArgumentNotValid.checkNotNull(c, "Connection c"); PreparedStatement s = c.prepareStatement( "CREATE TEMPORARY TABLE " + "jobconfignames " + "( domain_name varchar(" + Constants.MAX_NAME_SIZE + "), " + " config_name varchar(" + Constants.MAX_NAME_SIZE + ") )"); s.execute(); s.close(); return "jobconfignames"; }
From source file:com.l2jfree.gameserver.network.L2Client.java
public void markRestoredChar(int charslot) throws Exception { // have to make sure active character must be nulled /*//w ww . j a v a 2 s . com * if (getActiveChar() != null) { saveCharToDisk (getActiveChar()); if * (_log.isDebugEnabled()) _log.debug("active Char saved"); _activeChar * = null; } */ int objid = getObjectIdForSlot(charslot); if (objid < 0) return; Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?"); statement.setInt(1, objid); statement.execute(); statement.close(); } catch (Exception e) { _log.error("Error restoring character.", e); } finally { L2DatabaseFactory.close(con); } }
From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java
/** * Add user details in Back Channeling Scenario * * @param backChannelUserDetails BackChannelRequestDetails *//*from ww w . jav a 2s . c o m*/ public static void addBackChannelRequestDetails(BackChannelRequestDetails backChannelUserDetails) throws ConfigurationException, CommonAuthenticatorException { Connection connection = null; PreparedStatement preparedStatement = null; String addUserDetailsQuery = "insert into backchannel_request_details(correlation_id,msisdn,notification_bearer_token," + "notification_url,request_initiated_time,client_id,redirect_url) values(?," + "?,?,?,NOW(),?,?);"; try { connection = getConnectDBConnection(); if (log.isDebugEnabled()) { log.debug("Executing the query " + addUserDetailsQuery); } preparedStatement = connection.prepareStatement(addUserDetailsQuery); preparedStatement.setString(1, backChannelUserDetails.getCorrelationId()); preparedStatement.setString(2, backChannelUserDetails.getMsisdn()); preparedStatement.setString(3, backChannelUserDetails.getNotificationBearerToken()); preparedStatement.setString(4, backChannelUserDetails.getNotificationUrl()); preparedStatement.setString(5, backChannelUserDetails.getClientId()); preparedStatement.setString(6, backChannelUserDetails.getRedirectUrl()); preparedStatement.execute(); } catch (SQLException e) { handleException("Error occurred while inserting user details for : " + backChannelUserDetails.getMsisdn() + "in " + "BackChannel Scenario.", e); } catch (NamingException e) { throw new ConfigurationException("DataSource could not be found in mobile-connect.xml"); } finally { closeAllConnections(preparedStatement, connection); } }
From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java
/** * Used to verify that the provided nonce is not used earlier in the past 5 minutes, make sure you called * verifyOAuthToken first/*from w w w .j a va 2 s . c o m*/ * @throws OAuthException Thrown if it was used earlier */ public void verifyOAuthNonce(Database database) throws SQLException, OAuthException { if (user == null) /* Should NEVER happen! */ throw new OAuthException("user is null!"); final String oauth_nonce = oauth_params.get(OAuthParameters.OAUTH_NONCE); PreparedStatement statement = database.getConnection().prepareStatement(NONCE_CHECKING_QUERY); statement.setString(1, oauth_nonce); statement.setInt(2, user.getUserId()); ResultSet result = statement.executeQuery(); if (result.first()) { result.close(); throw new OAuthException(ErrorMessages.USED_NONCE); } result.close(); PreparedStatement insertStatement = database.getConnection().prepareStatement(NONCE_INSERT_QUERY); insertStatement.setInt(1, user.getUserId()); insertStatement.setString(2, oauth_nonce); insertStatement.execute(); database.getConnection().commit(); }
From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java
private long saveAddress(Connection conn, Address address) { long id = -1; String sql = "insert into t_address(f_country, f_province, f_city, f_street, f_postcode)" + " values(?, ?, ?, ?, ?)"; try {/*from w w w .j a va 2 s . c o m*/ PreparedStatement preState = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); preState.setString(1, address.getCountry()); preState.setString(2, address.getProvince()); preState.setString(3, address.getCity()); preState.setString(4, address.getStreet()); preState.setString(5, address.getPostcode()); preState.execute(); id = generateId(preState); if (-1 != id) { address.setId(id); } } catch (SQLException e) { e.printStackTrace(); } return id; }