Java Code Examples for java.sql.PreparedStatement.executeUpdate()

The following are Jave code examples for showing how to use executeUpdate() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: polyevent   File: OrganizationDAO.java   View Source Code Vote up 7 votes
public void addMember(Organization organization, User user) {
    PreparedStatement preparedStatement = null;
    final String query = "INSERT INTO Members(user, organization) VALUES (?,?)";
    try {
        preparedStatement = initializePreparedStatement(query, false, user.getId(), organization.getId());
        int status  = preparedStatement.executeUpdate();
        if (status == 0) {
            throw  new DAOException("Impossible d'ajouter ce membre");
        } else {
            organization.addMember(user);
        }
    } catch (SQLException e) {
        throw new DAOException(e);
    } finally {
        close(preparedStatement);
    }
}
 
Example 2
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public void setMessageShared(Connection txn, MessageId m) throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE messages SET shared = TRUE"
				+ " WHERE messageId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBytes(1, m.getBytes());
		int affected = ps.executeUpdate();
		if (affected < 0 || affected > 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 3
Project: OnlineChecker-Spigot-SQL-Support   File: DeleteQuery.java   View Source Code Vote up 6 votes
public void execute() {
	PreparedStatement prest;
	try {
		prest = connection.prepareStatement(sql);

		int i = 1;
		for (Object object : values) {
			prest.setObject(i, object);
			i++;
		}
		prest.executeUpdate();
		prest.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 4
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public void setContactActive(Connection txn, ContactId c, boolean active)
		throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE contacts SET active = ? WHERE contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setBoolean(1, active);
		ps.setInt(2, c.getInt());
		int affected = ps.executeUpdate();
		if (affected < 0 || affected > 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 5
Project: aliyun-maxcompute-data-collectors   File: TestIncrementalImport.java   View Source Code Vote up 6 votes
/**
 * Insert rows with id = [low, hi) into tableName.
 */
private void insertIdRows(String tableName, int low, int hi)
    throws SQLException {
  SqoopOptions options = new SqoopOptions();
  options.setConnectString(SOURCE_DB_URL);
  HsqldbManager manager = new HsqldbManager(options);
  Connection c = manager.getConnection();
  PreparedStatement s = null;
  try {
    s = c.prepareStatement("INSERT INTO " + manager.escapeTableName(tableName) + " VALUES(?)");
    for (int i = low; i < hi; i++) {
      s.setInt(1, i);
      s.executeUpdate();
    }

    c.commit();
  } finally {
    if(s != null) {
      s.close();
    }
  }
}
 
Example 6
Project: AeroStory   File: NPCConversationManager.java   View Source Code Vote up 6 votes
public void addPandoraItem(int inv) {
MapleInventoryType type = MapleInventoryType.getByType((byte) inv);
Item pan = c.getPlayer().getInventory(type).getItem((byte) 0);
if (type == null || pan == null) {
return;
}
try {
Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO pandoraitems(itemid) VALUES (?)");
ps.setInt(1, pan.getItemId());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
	System.out.print("Error excuting MySQL.");
return;
}
MapleInventoryManipulator.removeFromSlot(c, type, (byte) 0, pan.getQuantity(), false);

}
 
Example 7
Project: uavstack   File: DAOFactory.java   View Source Code Vote up 6 votes
public int update(Object... args) throws SQLException {

            Connection conn = null;
            PreparedStatement st = null;
            try {
                conn = fac.getConnection();
                st = conn.prepareStatement(sqlTemplate);
                if (null != args && args.length > 0) {
                    int index = 1;
                    for (Object arg : args) {
                        setPrepareStatementParam(st, index, arg);
                        index++;
                    }
                }
                return st.executeUpdate();
            }
            catch (SQLException e) {
                throw e;
            }
            finally {
                bulidDAOThreadContext(conn, st);
            }
        }
 
Example 8
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public void setMessageState(Connection txn, MessageId m, State state)
		throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE messages SET state = ? WHERE messageId = ?";
		ps = txn.prepareStatement(sql);
		ps.setInt(1, state.getValue());
		ps.setBytes(2, m.getBytes());
		int affected = ps.executeUpdate();
		if (affected < 0 || affected > 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 9
Project: redesocial   File: EstadoDAO.java   View Source Code Vote up 6 votes
/**
*@author Warley Rodrigues
*Criação e inserção de Pais, Estado, Cidade, Usuario e Postagem no banco de dados
*/ 
@Override
public void alterar(Estado p) throws SQLException, Exception {
    Connection conexao = getConexao();

    PreparedStatement pstmt;
    pstmt = conexao.prepareStatement("update estados set nome = ?, pais = ? where id = ?");

    pstmt.setString(1, p.getNome());
    pstmt.setInt(2, p.getPais().getId());
    pstmt.setInt(3, p.getId());
    
  // executa uma inserção
  
    pstmt.executeUpdate();
}
 
Example 10
Project: aliyun-maxcompute-data-collectors   File: SQLServerHiveImportManualTest.java   View Source Code Vote up 5 votes
/**
 * Drop a table if it already exists in the database.
 * @param table
 *            the name of the table to drop.
 * @throws SQLException
 *             if something goes wrong.
 */
protected void dropTableIfExists(String table) throws SQLException {
  Connection conn = getManager().getConnection();
  String sqlStmt = "IF OBJECT_ID('" + table
      + "') IS NOT NULL  DROP TABLE " + table;
  PreparedStatement statement = conn.prepareStatement(sqlStmt,
      ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  try {
    statement.executeUpdate();
    conn.commit();
  } finally {
    statement.close();
  }
}
 
Example 11
Project: aliyun-maxcompute-data-collectors   File: TestExportUpdate.java   View Source Code Vote up 5 votes
/**
 * <p>Creates a table with three columns - A INT, B INT and C VARCHAR(32).
 * This table is populated with records in a set of three with total records
 * with the total number of unique values of A equal to the specified aMax
 * value. For each value of A, there will be three records with value of
 * B ranging from 0-2, and a corresponding value of C.</p>
 * <p>For example if <tt>aMax = 2</tt>, the table will contain the
 * following records:
 * <pre>
 *    A   |   B   |  C
 * ----------------------
 *    0   |   0   | 0foo0
 *    0   |   1   | 0foo1
 *    0   |   2   | 0foo2
 *    1   |   0   | 1foo0
 *    1   |   1   | 1foo1
 *    1   |   2   | 1foo2
 * </pre></p>
 * @param aMax the number of
 * @throws SQLException
 */
private void createMultiKeyTable(int aMax) throws SQLException {
  Connection conn = getConnection();

  PreparedStatement statement = conn.prepareStatement(
      "CREATE TABLE " + getTableName()
      + " (A INT NOT NULL, B INT NOT NULL, C VARCHAR(32))");
  try {
    statement.executeUpdate();
    conn.commit();
  } finally {
    statement.close();
    statement = null;
  }

  try {
    for (int i = 0; i< aMax; i++) {
      for (int j = 0; j < 3; j++) {
        statement = conn.prepareStatement("INSERT INTO " + getTableName()
            + " VALUES (" + i + ", " + j + ", '"
            + i + "foo" + j + "')");
        statement.executeUpdate();
        statement.close();
        statement = null;
      }
    }
  } finally {
    if (null != statement) {
      statement.close();
    }
  }

  conn.commit();
}
 
Example 12
Project: OnlineChecker-Spigot-SQL-Support   File: SetupSQL.java   View Source Code Vote up 5 votes
public SetupSQL() {
	try {
		String hostname = Core.getInstance().sqlConfig.get().getString("sql.hostname");
		String portnumber = Core.getInstance().sqlConfig.get().getString("sql.port");
		String database = Core.getInstance().sqlConfig.get().getString("sql.database"); 
		String username = Core.getInstance().sqlConfig.get().getString("sql.username"); 
		String password = Core.getInstance().sqlConfig.get().getString("sql.password");
		sqla = new SQLConnection(hostname, portnumber, database, username, password);
		co = sqla.getConnection();
		PreparedStatement sql = co
				.prepareStatement(
						  "CREATE TABLE IF NOT EXISTS cache(uuid VARCHAR(255) NOT NULL PRIMARY KEY, name VARCHAR(100), totaltime INT default 0, firstjoined VARCHAR(100))");
		table = new Table(co, "cache");
		sql.executeUpdate();
		Core.getInstance().getLogger().info("Succesfull connected to MYSQL");
		valid = true;
	} catch (Exception e) {
		Core.getInstance().getLogger().info("-------- !WARNING! --------");
		Core.getInstance().getLogger().info("Can't connect to your SQL server. Make sure SQL.yml is correct.... Shutting down..");
		Core.getInstance().getLogger().warning("PROBLEM: "+e.getMessage());
		Core.getInstance().getLogger().info("-------- !WARNING! --------");
		Core.getInstance().getPluginLoader().disablePlugin(Core.getInstance());
		valid = false;
		return;
	}

}
 
Example 13
Project: ohtu_miniprojekti   File: SQLSuggestionDao.java   View Source Code Vote up 5 votes
@Override
public void remove(Suggestion s) {
    try {
        Connection connection = database.getConnection();
        PreparedStatement stmt = connection.prepareStatement("DELETE FROM Suggestion WHERE id = ?");
        stmt.setInt(1, s.getId());
        stmt.executeUpdate();

        stmt.close();
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: BibliotecaPS   File: StatementRegressionTest.java   View Source Code Vote up 5 votes
private void testCsc4194InsertCheckText(Connection c, String tableName, String encoding) throws Exception {
    byte[] kabuInShiftJIS = { (byte) 0x87, // a double-byte charater("kabu") in Shift JIS
            (byte) 0x8a, };

    String expected = new String(kabuInShiftJIS, encoding);
    PreparedStatement testStmt = c.prepareStatement("INSERT INTO " + tableName + " VALUES (?)");
    testStmt.setString(1, expected);
    testStmt.executeUpdate();

    this.rs = c.createStatement().executeQuery("SELECT field1 FROM " + tableName);
    assertTrue(this.rs.next());
    assertEquals(expected, this.rs.getString(1));
    this.rs.close();
}
 
Example 15
Project: LogisticApp   File: RotaDAOSQL.java   View Source Code Vote up 5 votes
@Override
public void update(Rota rota) throws Exception {
	PreparedStatement pstm = this.getConnectionFactory().getConnection()
			.prepareStatement(RotaQueries.UPDATE_ROTA.getConsulta());
	pstm.setInt(1, rota.getId());
	pstm.setString(2, rota.getNome());
	pstm.setObject(3, (rota.getOrigem() == null) ? null : rota.getOrigem().getId());
	pstm.setObject(4, (rota.getDestino() == null) ? null : rota.getDestino().getId());
	pstm.setDouble(7, rota.getCustoGrama());
	pstm.setInt(8, rota.getTempoEntrega());
	pstm.setInt(10, rota.getId());
	if (rota instanceof Direta) {
		Direta direta = (Direta) rota;
		pstm.setDouble(5, direta.getCapacidadeTotal());
		pstm.setDouble(6, direta.getCapacidadeAlocada());
		pstm.setString(9, "D");
	} else if (rota instanceof Fracional) {
		pstm.setObject(5, null);
		pstm.setObject(6, null);
		pstm.setString(9, "F");
	}
	try {
		pstm.executeUpdate();
		if (rota instanceof Fracional)
			this.updateTrechos((Fracional) rota);
	} catch (Exception ex) {
		throw new LogisticException("Erro durante a rotina de atualização de rotas.");
	}
}
 
Example 16
Project: spanner-jdbc   File: DMLTester.java   View Source Code Vote up 5 votes
private void runBulkUpdateTests() throws SQLException
{
	log.info("Starting bulk update test");
	String sql = "UPDATE TEST SET DESCRIPTION='Divisble by three' WHERE MOD(ID, 3)=0";
	PreparedStatement statement = connection.prepareStatement(sql);
	statement.executeUpdate();
	connection.commit();
	verifyTableContents("SELECT DESCRIPTION FROM TEST WHERE ID=3", "Divisble by three");
	log.info("Finished bulk update test");
}
 
Example 17
Project: redesocial   File: TiposAtividadesDAO.java   View Source Code Vote up 5 votes
@Override
public void excluir(int id) throws Exception {
    Connection conexao = getConexao();

    PreparedStatement pstmt;
    pstmt = conexao.prepareStatement("delete from tipos_atividades where id = ?");

    pstmt.setInt(1, id);
    pstmt.executeUpdate();
}
 
Example 18
Project: Progetto-M   File: ManagerGoal.java   View Source Code Vote up 5 votes
@Override
public void updateMinutoGoal(int idPartita, int minuto, int numeroGiocatore, String nomeSquadra, String cittaSquadra, String nomeTorneo, int annoTorneo, int nuovoMinuto) throws RemoteException {
    try{
        query= "UPDATE GOAL\n "
                + "SET MINUTO = '" + nuovoMinuto + "'\n "
                + "WHERE IDPARTITA = '" + idPartita + "' AND MINUTO = '" + minuto + "' AND NUMEROGIOCATORE = '" + numeroGiocatore + "' AND NOMESQUADRA = '" + nomeSquadra.toUpperCase() + "' AND CITTASQUADRA = '" + cittaSquadra.toUpperCase() + "' AND NOMETORNEO = '" + nomeTorneo.toUpperCase() + "' AND ANNOTORNEO = '" + annoTorneo + "' ;";
        PreparedStatement posted = DatabaseConnection.connection.prepareStatement(query);
        posted.executeUpdate(query);
    }catch(SQLException ex){
        System.out.println("ERROR:" + ex);
    } 
}
 
Example 19
Project: BibliotecaPS   File: StatementRegressionTest.java   View Source Code Vote up 4 votes
public void testBug5450() throws Exception {
    if (versionMeetsMinimum(4, 1)) {
        String table = "testBug5450";
        String column = "policyname";

        try {
            Properties props = new Properties();
            props.setProperty("characterEncoding", "utf-8");

            Connection utf8Conn = getConnectionWithProps(props);
            Statement utfStmt = utf8Conn.createStatement();

            this.stmt.executeUpdate("DROP TABLE IF EXISTS " + table);

            this.stmt.executeUpdate("CREATE TABLE " + table + "(policyid int NOT NULL AUTO_INCREMENT, " + column + " VARCHAR(200), "
                    + "PRIMARY KEY(policyid)) DEFAULT CHARACTER SET utf8");

            String pname0 = "inserted \uac00 - foo - \u4e00";

            utfStmt.executeUpdate("INSERT INTO " + table + "(" + column + ") VALUES (\"" + pname0 + "\")");

            this.rs = utfStmt.executeQuery("SELECT " + column + " FROM " + table);

            this.rs.first();
            String pname1 = this.rs.getString(column);

            assertEquals(pname0, pname1);
            byte[] bytes = this.rs.getBytes(column);

            String pname2 = new String(bytes, "utf-8");
            assertEquals(pname1, pname2);

            utfStmt.executeUpdate("delete from " + table + " where " + column + " like 'insert%'");

            PreparedStatement s1 = utf8Conn.prepareStatement("insert into " + table + "(" + column + ") values (?)");

            s1.setString(1, pname0);
            s1.executeUpdate();

            String byteesque = "byte " + pname0;
            byte[] newbytes = byteesque.getBytes("utf-8");

            s1.setBytes(1, newbytes);
            s1.executeUpdate();

            this.rs = utfStmt.executeQuery("select " + column + " from " + table + " where " + column + " like 'insert%'");
            this.rs.first();
            String pname3 = this.rs.getString(column);
            assertEquals(pname0, pname3);

            this.rs = utfStmt.executeQuery("select " + column + " from " + table + " where " + column + " like 'byte insert%'");
            this.rs.first();

            String pname4 = this.rs.getString(column);
            assertEquals(byteesque, pname4);

        } finally {
            this.stmt.executeUpdate("DROP TABLE IF EXISTS " + table);
        }
    }
}
 
Example 20
Project: BibliotecaPS   File: StringRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests that 'latin1' character conversion works correctly.
 * 
 * @throws Exception
 *             if any errors occur
 */
public void testLatin1Encoding() throws Exception {
    char[] latin1Charset = { 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F,
            0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x0021,
            0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033,
            0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045,
            0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
            0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069,
            0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007A, 0x007B,
            0x007C, 0x007D, 0x007E, 0x007F, 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D,
            0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F,
            0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1,
            0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3,
            0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5,
            0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
            0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9,
            0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF };

    String latin1String = new String(latin1Charset);
    Connection latin1Conn = null;
    PreparedStatement pStmt = null;

    try {
        Properties props = new Properties();
        props.put("characterEncoding", "cp1252");
        latin1Conn = getConnectionWithProps(props);

        createTable("latin1RegressTest", "(stringField TEXT)");

        pStmt = latin1Conn.prepareStatement("INSERT INTO latin1RegressTest VALUES (?)");
        pStmt.setString(1, latin1String);
        pStmt.executeUpdate();

        ((com.mysql.jdbc.Connection) latin1Conn).setTraceProtocol(true);

        this.rs = this.stmt.executeQuery("SELECT * FROM latin1RegressTest");
        ((com.mysql.jdbc.Connection) latin1Conn).setTraceProtocol(false);

        this.rs.next();

        String retrievedString = this.rs.getString(1);

        System.out.println(latin1String);
        System.out.println(retrievedString);

        if (!retrievedString.equals(latin1String)) {
            int stringLength = Math.min(retrievedString.length(), latin1String.length());

            for (int i = 0; i < stringLength; i++) {
                char rChar = retrievedString.charAt(i);
                char origChar = latin1String.charAt(i);

                if ((rChar != '?') && (rChar != origChar)) {
                    fail("characters differ at position " + i + "'" + rChar + "' retrieved from database, original char was '" + origChar + "'");
                }
            }
        }
    } finally {
        if (latin1Conn != null) {
            latin1Conn.close();
        }
    }
}