package com.juick.server; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author ugnich */ public class VotesQueries { public static boolean voteMessage(Connection sql, int mid, int uid, int vote) { boolean ret = false; PreparedStatement stmt = null; try { stmt = sql.prepareStatement("INSERT INTO messages_votes(message_id,user_id,vote) VALUES (?,?,?)"); stmt.setInt(1, mid); stmt.setInt(2, uid); stmt.setInt(3, vote); ret = stmt.executeUpdate() > 0; } catch (SQLException e) { System.err.println(e); } finally { Utils.finishSQL(null, stmt); } if (ret) { try { String query; if (vote > 0) { query = "UPDATE messages SET votes=votes+1 WHERE message_id=?"; } else { query = "UPDATE messages SET votes=votes-1 WHERE message_id=?"; } stmt = sql.prepareStatement(query); stmt.setInt(1, mid); stmt.executeUpdate(); } catch (SQLException e) { System.err.println(e); } finally { Utils.finishSQL(null, stmt); } } return ret; } public static int getMessageVotes(Connection sql, int mid) { return SQLHelpers.getInt(sql, "SELECT votes FROM messages WHERE message_id=?", mid, 0); } public static boolean fillMessagesVotes(Connection sql, ArrayList msgs, int vuid) { boolean ret = false; String mids = ""; final int midsSize = msgs.size(); for (int i = 0; i < midsSize; i++) { if (i > 0) { mids += ","; } mids += msgs.get(i).MID; } PreparedStatement stmt = null; ResultSet rs = null; try { stmt = sql.prepareStatement("SELECT message_id,vote FROM messages_votes WHERE user_id=? AND message_id IN (" + mids + ")"); stmt.setInt(1, vuid); rs = stmt.executeQuery(); rs.beforeFirst(); while (rs.next()) { int mid = rs.getInt(1); for (int i = 0; i < midsSize; i++) { if (msgs.get(i).MID == mid) { msgs.get(i).UserVote = rs.getInt(2); ret = true; } } } } catch (SQLException e) { System.err.println(e); } finally { Utils.finishSQL(rs, stmt); } return ret; } }