List of usage examples for java.sql PreparedStatement executeUpdate
int executeUpdate() throws SQLException;
PreparedStatement
object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT
, UPDATE
or DELETE
; or an SQL statement that returns nothing, such as a DDL statement. From source file:com.wso2telco.historylog.DbTracelog.java
/** * Log history./*w w w .ja v a 2 s . c o m*/ * * @param Reqtype the reqtype * @param isauthenticated the isauthenticated * @param application the application * @param authUser the auth user * @param authenticators the authenticators * @param ipaddress the ipaddress * @throws LogHistoryException the log history exception */ public static void LogHistory(String Reqtype, boolean isauthenticated, String application, String authUser, String authenticators, String ipaddress) throws LogHistoryException { Connection con = null; PreparedStatement pst = null; try { con = DbTracelog.getMobileDBConnection(); String sql = "INSERT INTO sp_login_history (reqtype, application_id, authenticated_user, isauthenticated," + " authenticators,ipaddress, created, created_date)" + " VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?)"; pst = con.prepareStatement(sql); pst.setString(1, Reqtype); pst.setString(2, application); pst.setString(3, authUser); pst.setInt(4, (isauthenticated ? 1 : 0)); pst.setString(5, authenticators); pst.setString(6, ipaddress); pst.setString(7, "authUser"); pst.setTimestamp(8, new java.sql.Timestamp(new java.util.Date().getTime())); pst.executeUpdate(); } catch (SQLException e) { handleException( "Error occured while Login SP LogHistory: " + application + " Service Provider: " + authUser, e); } finally { DbUtil.closeAllConnections(pst, con, null); } }
From source file:hnu.helper.DataBaseConnection.java
/** * Create and Execute an SQL PreparedStatement and returns true if * everything went ok. Can be used for DML and DDL. * Borrows from apache.commons.scaffold.sql.StatementUtils (see * jakarta-commons-sandbox/scaffold)//from w ww . j a va 2 s. c o m */ public static boolean execute(String sql, Object[] parameters) { DataBaseConnection db = new DataBaseConnection(); boolean returnValue = false; Connection conn = db.getDBConnection(); PreparedStatement pStmt = null; Statement stmt = null; log.debug("About to execute: " + sql); try { if (parameters == null || (parameters.length == 0)) { stmt = conn.createStatement(); stmt.executeUpdate(sql); } else { pStmt = conn.prepareStatement(sql); for (int i = 0; i < parameters.length; i++) { log.debug("parameter " + i + ": " + parameters[i]); pStmt.setObject(i + 1, parameters[i]); } pStmt.executeUpdate(); } log.debug(".. executed without exception (hope to return 'true') "); returnValue = true; } catch (SQLException ex) { log.error("Error executing: '" + sql + "'", ex); returnValue = false; } finally { try { if (stmt != null) { stmt.close(); } if (pStmt != null) { pStmt.close(); } if (conn != null) { conn.close(); } } catch (Exception ex) { log.error("Couldn't close the statement or connection.", ex); } } return returnValue; }
From source file:edu.lafayette.metadb.model.userman.UserManDAO.java
/** * Create a new user/*from w w w . j a v a 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:dk.netarkivet.harvester.datamodel.JobDAOTester.java
public static void changeStatus(long jobID, JobStatus newStatus) { PreparedStatement s = null; Connection c = HarvestDBConnection.get(); try {//w ww. ja va 2 s . c o m s = c.prepareStatement("update jobs set status=? where job_id=?"); s.setLong(1, newStatus.ordinal()); s.setLong(2, jobID); s.executeUpdate(); } catch (SQLException e) { String message = "SQL error changing job state for job with id=" + jobID + " in database"; throw new IOFailure(message, e); } finally { HarvestDBConnection.release(c); } }
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 */// w w w. j av a 2s .c o m 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.stratelia.webactiv.util.DBUtil.java
private static int updateMaxFromTable(Connection connection, String tableName) throws SQLException { String table = tableName.toLowerCase(Locale.ROOT); int max = 0;//from ww w.ja v a2 s . c o m PreparedStatement prepStmt = null; int count = 0; try { prepStmt = connection.prepareStatement("UPDATE UniqueId SET maxId = maxId + 1 WHERE tableName = ?"); prepStmt.setString(1, table); count = prepStmt.executeUpdate(); connection.commit(); } catch (SQLException sqlex) { rollback(connection); throw sqlex; } finally { close(prepStmt); } if (count == 1) { PreparedStatement selectStmt = null; ResultSet rs = null; try { // l'update c'est bien passe, on recupere la valeur selectStmt = connection.prepareStatement("SELECT maxId FROM UniqueId WHERE tableName = ?"); selectStmt.setString(1, table); rs = selectStmt.executeQuery(); if (!rs.next()) { SilverTrace.error("util", "DBUtil.getNextId", "util.MSG_NO_RECORD_FOUND"); throw new RuntimeException("Erreur Interne DBUtil.getNextId()"); } max = rs.getInt(1); } finally { close(rs, selectStmt); } return max; } throw new SQLException("Update impossible : Ligne non existante"); }
From source file:com.wso2.raspberrypi.Util.java
public static void registerRaspberryPi(String macAddress, String ipAddress) { System.out.println("Registering Raspberry Pi: " + macAddress + "/" + ipAddress); BasicDataSource ds = getBasicDataSource(); Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet rs = null;/* w w w .j av a2 s .c o m*/ try { dbConnection = ds.getConnection(); prepStmt = dbConnection.prepareStatement("SELECT * FROM RASP_PI WHERE mac='" + macAddress + "'"); rs = prepStmt.executeQuery(); if (rs.next()) { // If it exists prepStmt = dbConnection.prepareStatement("UPDATE RASP_PI SET ip='" + ipAddress + "',last_updated='" + System.currentTimeMillis() + "' WHERE mac='" + macAddress + "'"); prepStmt.executeUpdate(); } else { prepStmt = dbConnection.prepareStatement("INSERT INTO RASP_PI (mac,ip,last_updated) VALUES ('" + macAddress + "','" + ipAddress + "','" + System.currentTimeMillis() + "' )"); prepStmt.execute(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (dbConnection != null) { dbConnection.close(); } if (prepStmt != null) { prepStmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
From source file:fll.web.admin.UploadSubjectiveData.java
/** * Remove rows from the specified subjective category that are empty. These * are rows that have null for all scores and is not a no show. * //from www .j a v a 2 s. co m * @param currentTournament * @param connection * @param categoryName * @param categoryElement * @throws SQLException */ @SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns are dynamic") private static void removeNullRows(final int currentTournament, final Connection connection, final String categoryName, final ScoreCategory categoryElement) throws SQLException { final List<AbstractGoal> goalDescriptions = categoryElement.getGoals(); PreparedStatement prep = null; try { final StringBuffer sql = new StringBuffer(); sql.append("DELETE FROM " + categoryName + " WHERE NoShow <> ? "); for (final AbstractGoal goalDescription : goalDescriptions) { sql.append(" AND " + goalDescription.getName() + " IS NULL "); } sql.append(" AND Tournament = ?"); prep = connection.prepareStatement(sql.toString()); prep.setBoolean(1, true); prep.setInt(2, currentTournament); prep.executeUpdate(); } finally { SQLFunctions.close(prep); } }
From source file:database.HashTablesTools.java
private static int enterInPDBfilesHashDB(Connection connexion, String hash, String fourLetterCode, String tableName, char[] chainType, char[] chainName, String sequence) { try {/*from www. j a va 2 s . c o m*/ String insertTableSQL = "INSERT INTO " + tableName + " " + "(pdbfilehash, fourLettercode, chainId, chainType, sequenceString) VALUES" + "(?,?,?,?,?)"; PreparedStatement preparedStatement = connexion.prepareStatement(insertTableSQL); preparedStatement.setString(1, hash); preparedStatement.setString(2, String.valueOf(fourLetterCode)); preparedStatement.setString(3, String.valueOf(chainName)); preparedStatement.setString(4, String.valueOf(chainType)); preparedStatement.setString(5, sequence); int ok = preparedStatement.executeUpdate(); preparedStatement.close(); System.out.println(ok + " raw created " + String.valueOf(fourLetterCode) + " " + String.valueOf(chainName) + " " + String.valueOf(chainType)); // + " " + sequence); return 1; } catch (SQLException e1) { System.out.println("Failed to enter entry in " + tableName + " table "); return 0; } }
From source file:com.trackplus.ddl.DataWriter.java
private static void insertClobData(Connection con, String line) throws DDLException { /*//from w w w . ja va 2 s . c om "OBJECTID",//Integer not null "EXCHANGEDIRECTION",//Integer not null "ENTITYID",//Integer not null "ENTITYTYPE",//Integer not null "FILENAME",//Varchar(255) "CHANGEDBY",//Integer "LASTEDIT",//Timestamp "TPUUID",//Varchar(36) "FILECONTENT"//Blob sub_type 1 */ String sql = "INSERT INTO TMSPROJECTEXCHANGE(OBJECTID, EXCHANGEDIRECTION, ENTITYID,ENTITYTYPE,FILENAME,CHANGEDBY,LASTEDIT,TPUUID,FILECONTENT) " + "VALUES(?,?,?,?,?,?,?,?,?)"; StringTokenizer st = new StringTokenizer(line, ","); Integer objectID = Integer.valueOf(st.nextToken()); Integer exchangeDirection = Integer.valueOf(st.nextToken()); Integer entityID = Integer.valueOf(st.nextToken()); Integer entityType = Integer.valueOf(st.nextToken()); String fileName = st.nextToken(); if ("null".equalsIgnoreCase(fileName)) { fileName = null; } Integer changedBy = null; try { changedBy = Integer.valueOf(st.nextToken()); } catch (Exception ex) { LOGGER.debug(ex); } Timestamp lastEdit = null; String lastEditStr = st.nextToken(); if (lastEditStr != null) { try { lastEdit = Timestamp.valueOf(lastEditStr); } catch (Exception ex) { LOGGER.debug(ex); } } String tpuid = st.nextToken(); String base64Str = st.nextToken(); if (base64Str.length() == 1 && " ".equals(base64Str)) { base64Str = ""; } byte[] bytes = Base64.decodeBase64(base64Str); String fileContent = new String(bytes); try { PreparedStatement preparedStatement = con.prepareStatement(sql); preparedStatement.setInt(1, objectID); preparedStatement.setInt(2, exchangeDirection); preparedStatement.setInt(3, entityID); preparedStatement.setInt(4, entityType); preparedStatement.setString(5, fileName); preparedStatement.setInt(6, changedBy); preparedStatement.setTimestamp(7, lastEdit); preparedStatement.setString(8, tpuid); preparedStatement.setString(9, fileContent); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new DDLException(e.getMessage(), e); } }