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

The following are Jave code examples for showing how to use setInt() 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: DBus   File: SqlManager.java   View Source Code Vote up 6 votes
private void setFullPullReqTblSqlParam(PreparedStatement pStmt, String startTime, String completedTime,
        String pullStatus, String errorMsg, int seqno) throws SQLException {
    int paraIndex = 1;
    if(pStmt != null){
        if(StringUtils.isNotEmpty(startTime)){
            pStmt.setString(paraIndex, startTime);
            paraIndex++;
        }
        if (StringUtils.isNotEmpty(completedTime)){
            pStmt.setString(paraIndex, completedTime);
            paraIndex++;
        }
        if (StringUtils.isNotEmpty(pullStatus)) {
            pStmt.setString(paraIndex, pullStatus);
            paraIndex++;
        }
        if (StringUtils.isNotEmpty(errorMsg)) {
            errorMsg = errorMsg.length()>1000?errorMsg.substring(0,1000):errorMsg;
            pStmt.setString(paraIndex, errorMsg);
            paraIndex++;
        }
        pStmt.setInt(paraIndex, seqno);
    }
}
 
Example 2
Project: s-store   File: TestJDBCQueries.java   View Source Code Vote up 6 votes
private void populateContestants() {
    String q = "insert into contestants values(?, ?)";
    for (int i = 0; i < TABLE_SIZE; i++) {
        try {
            PreparedStatement sel = conn.prepareStatement(q);
            
            sel.setInt(1, i);
            sel.setString(2, "constants" + i);
            sel.execute();
            int count = sel.getUpdateCount();
            assertTrue(count==1);
        }
        catch(SQLException e) {
            System.err.printf("ERROR(INSERT): %s value='%s': %s\n",
                    "votes", i, e.getMessage());
            fail();
        }
    }
}
 
Example 3
Project: tcp   File: SqlInserts.java   View Source Code Vote up 6 votes
public static boolean insertAvanceCualitativo(AvanceCualitativo avanceCualitativo, String usuarioResponsable)throws ParseException{
	try {
		Connection conn=ConnectionConfiguration.conectar();

		String query = " insert into avance_cualitativo (accion_catalogo_id, ins_linea_accion_id, trimestre_id, gestiones_realizadas, principales_logros_alcanzados, dificultades_lecciones_aprendidas, objetivos_del_siguiente_trimestre, usuario_responsable)"
	+ " values (?, ?, ?, ?, ?, ?, ?, ?)";
		
		PreparedStatement insert = conn.prepareStatement(query);
		
		insert.setInt (1, avanceCualitativo.getAccionCatalogoId());
		insert.setInt (2, avanceCualitativo.getInsLineaAccionId());
		insert.setInt (3, avanceCualitativo.getTrimestreId());
		insert.setString (4, avanceCualitativo.getGestionesRealizadas());
		insert.setString (5, avanceCualitativo.getPrincipalesLogrosAlcanzados());
		insert.setString (6, avanceCualitativo.getDificultadesLeccionesAprendidas());
		insert.setString (7, avanceCualitativo.getObjetivosTrimestre());
		insert.setString (8, usuarioResponsable);
		
		insert.execute();
		   
		conn.close();
		return true;
	} catch (SQLException e) {e.printStackTrace(); return false;}
	
}
 
Example 4
Project: spr   File: SqlHelper.java   View Source Code Vote up 6 votes
public static void insertTpoPrograma(int codTipoPrograma,  int numero_fila, int anio, String nombreTipoPrograma, String abrev){
 	 Connection conect=conectar();
 String query = " insert into tipo_presupuesto (id, numero_fila, anho, nombre, descipcion, abrev)"
	        + " values (?,?,?,?,?,?)";
try {
	
	PreparedStatement preparedStmt;
	preparedStmt = conect.prepareStatement(query);
	preparedStmt.setInt (1, codTipoPrograma);
	preparedStmt.setInt (2, numero_fila);
	preparedStmt.setInt (3, anio);
    preparedStmt.setString (4, nombreTipoPrograma);
    preparedStmt.setString	(5, "");
    preparedStmt.setString	(6, abrev);
    preparedStmt.execute();
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
Example 5
Project: big_data   File: DimensionConverterImpl.java   View Source Code Vote up 6 votes
/**
 * 设置参数
 * 
 * @param pstmt
 * @param dimension
 * @throws SQLException
 */
private void setArgs(PreparedStatement pstmt, BaseDimension dimension) throws SQLException {
	int i = 0;
	if (dimension instanceof DateDimension) {
		DateDimension date = (DateDimension) dimension;
		pstmt.setInt(++i, date.getYear());
		pstmt.setInt(++i, date.getSeason());
		pstmt.setInt(++i, date.getMonth());
		pstmt.setInt(++i, date.getWeek());
		pstmt.setInt(++i, date.getDay());
		pstmt.setString(++i, date.getType());
		pstmt.setDate(++i, new Date(date.getCalendar().getTime()));
	} else if (dimension instanceof PlatformDimension) {
		PlatformDimension platform = (PlatformDimension) dimension;
		pstmt.setString(++i, platform.getPlatformName());
	} else if (dimension instanceof BrowserDimension) {
		BrowserDimension browser = (BrowserDimension) dimension;
		pstmt.setString(++i, browser.getBrowserName());
		pstmt.setString(++i, browser.getBrowserVersion());
	}
}
 
Example 6
Project: otus_java_2017_06   File: PreparedExecutor.java   View Source Code Vote up 6 votes
public void execUpdate(Map<Integer, String> idToName) {
    try {
        getConnection().setAutoCommit(false);
        String update = "insert into users(id, user_name) values(?,?)";
        PreparedStatement stmt = getConnection().prepareStatement(update);

        for (Integer id : idToName.keySet()) {
            stmt.setInt(1, id);
            stmt.setString(2, idToName.get(id));
            stmt.executeUpdate();
        }
        getConnection().commit();
        stmt.close();
    } catch (SQLException e) {
        try {
            getConnection().rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
}
 
Example 7
Project: ShowMilhaoPOOJava   File: PerguntaDAO.java   View Source Code Vote up 6 votes
/**	 
 * Método para remover perguntas do Banco de Dados
 */
@Autor("Divino Matheus")
public ModelPergunta remover(ModelPergunta modelPergunta) {
	abrirConexao();		
	try {
		String sql = "DELETE FROM perguntas WHERE id=?";
		PreparedStatement stmt = this.conexao.prepareStatement(sql);	
		stmt.setInt(1, modelPergunta.getId());
		stmt.executeUpdate();
		stmt.close();	
           JOptionPane.showMessageDialog(null, "Pergunta removida com sucesso!", "Processo concluído!", -1);
	} catch (Exception e) {			
		e.getMessage();
	} finally {			
		fecharConexao();
	}
	return null;		
}
 
Example 8
Project: oscm   File: DatabaseUpgradeHandler.java   View Source Code Vote up 6 votes
/**
 * Sets the specified version information in the version table in the
 * database.
 * 
 * @param conn
 *            The database connection.
 * @param versionInfoToSet
 *            The version information to be set.
 * @throws SQLException
 */
private void setVersionInformation(Connection conn,
        DatabaseVersionInfo versionInfoToSet, long time)
        throws SQLException {
    Statement stmt = conn.createStatement();
    try {
        stmt.execute("DELETE FROM VERSION");
    } finally {
        closeStatement(stmt);
    }

    PreparedStatement pStmt = conn
            .prepareStatement("INSERT INTO VERSION(productMajorVersion, productMinorVersion, schemaVersion, migrationDate) VALUES(?,?,?,?)");
    try {
        pStmt.setInt(1, versionInfoToSet.getProductMajorVersion());
        pStmt.setInt(2, versionInfoToSet.getProductMinorVersion());
        pStmt.setInt(3, versionInfoToSet.getSchemaVersion());
        pStmt.setTimestamp(4, new Timestamp(time));
        pStmt.execute();
    } finally {
        closeStatement(pStmt);
    }
}
 
Example 9
Project: bbm487s2017g1   File: Query.java   View Source Code Vote up 6 votes
public static boolean getWaitListBook(int user_id, int book_id){

        PreparedStatement statement;
        String query = String.format("SELECT * FROM %s WHERE user_id=? AND book_id=?", waitListTable);

        try {
            statement = MySQL.getInstance().getConnection().prepareStatement(query);
            statement.setInt(1,user_id);
            statement.setInt(2,book_id);
            ResultSet resultSet= statement.executeQuery();

            // check isEmpty
            if (!resultSet.next()) {
                return false;
            }

            return true;

        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
Example 10
Project: avengers-db   File: HeroDAO.java   View Source Code Vote up 6 votes
public int createHero(String name, String realname) throws SQLException{
	
	String query = "INSERT INTO `heroes` (`name`, `sex`, `likes`, `dislikes`, `picture`, `abilities`, `history`) VALUES (?, '', '0', '0', NULL, NULL, NULL)";
	Connection connect = connectToMySQL();
	PreparedStatement statement = connect.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
	statement.setString(1, name);
	statement.execute();
	ResultSet rs = statement.getGeneratedKeys();
	int id = -1;
	if(rs.next()){
		id = rs.getInt(1);
	}
	
	System.out.println("id " + id);
	
	String queryirl = "INSERT INTO `irl` (`hero_id`, `name`) VALUES (?,?)";
	PreparedStatement statementirl = connect.prepareStatement(queryirl, Statement.RETURN_GENERATED_KEYS);
	statementirl.setInt(1, id);
	statementirl.setString(2, realname);
	statementirl.execute();
	
	connect.close();
	return id;
	
}
 
Example 11
Project: Nird2   File: JdbcDatabase.java   View Source Code Vote up 6 votes
@Override
public int countOfferedMessages(Connection txn, ContactId c)
		throws DbException {
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		String sql = "SELECT COUNT (messageId) FROM offers "
				+ " WHERE contactId = ?";
		ps = txn.prepareStatement(sql);
		ps.setInt(1, c.getInt());
		rs = ps.executeQuery();
		if (!rs.next()) throw new DbException();
		int count = rs.getInt(1);
		if (rs.next()) throw new DbException();
		rs.close();
		ps.close();
		return count;
	} catch (SQLException e) {
		tryToClose(rs);
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
Example 12
Project: dev-courses   File: TestCacheSize.java   View Source Code Vote up 5 votes
void selectZip() {

        StopWatch        sw        = new StopWatch();
        java.util.Random randomgen = new java.util.Random();
        int              i         = 0;
        boolean          slow      = false;

        try {
            PreparedStatement ps = cConnection.prepareStatement(
                "SELECT TOP 1 firstname,lastname,zip,filler FROM test WHERE zip = ?");

            for (; i < bigops; i++) {
                ps.setInt(1, nextIntRandom(randomgen, smallrows));
                ps.execute();

                if ((i + 1) == 100 && sw.elapsedTime() > 50000) {
                    slow = true;
                }

                if (reportProgress && (i + 1) % 10000 == 0
                        || (slow && (i + 1) % 100 == 0)) {
                    System.out.println("Select " + (i + 1) + " : "
                                       + sw.elapsedTime() + " rps: "
                                       + (i * 1000 / (sw.elapsedTime() + 1)));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        long time = sw.elapsedTime();
        long rate = ((long) i * 1000) / (time + 1);

        storeResult("select random zip", i, time, rate);
        System.out.println("select time for random zip " + i + " rows  -- "
                           + time + " ms -- " + rate + " tps");
    }
 
Example 13
Project: ProyectoPacientes   File: StatementRegressionTest.java   View Source Code Vote up 5 votes
private void testBug74932ExecuteStmts(final Connection testConn, final String sqlOuter, final String sqlInner) throws SQLException {
    PreparedStatement psOuter = null;
    PreparedStatement psInner = null;
    ResultSet rsOuter = null;
    ResultSet rsInner = null;

    psOuter = testConn.prepareStatement(sqlOuter);
    psOuter.setInt(1, 1);
    rsOuter = psOuter.executeQuery();
    for (int i = 0; i < 2; i++) {
        assertTrue(rsOuter.next());
        try {
            psInner = testConn.prepareStatement(sqlInner);
            psInner.setInt(1, 2);
            rsInner = psInner.executeQuery();
            assertTrue(rsInner.next());
            assertTrue(rsInner.next());
            assertFalse(rsInner.next());
        } finally {
            if (rsInner != null) {
                rsInner.close();
            }
            psInner.close();
        }
    }
    assertFalse(rsOuter.next());
    rsOuter.close();
    rsInner.close();
    psOuter.close();
}
 
Example 14
Project: LojaDeInstrumentosMusicais   File: ProdutoDAO.java   View Source Code Vote up 5 votes
public Produto updateProduto(Produto produto) throws Exception{
    System.out.println("Atualizando produto...");
     String query = "UPDATE produtos SET codigoempresa=?, nome=?, descricao=?, codigofornecedor=?, codigocategoria=?, precocompra=?, precovenda=?, estoque=? WHERE codigo=?";
    
    
    try {
        PreparedStatement preparedStatement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        
        preparedStatement.setInt(1, produto.getCodigoempresa());
        preparedStatement.setString(2, produto.getNome());
        preparedStatement.setString(3, produto.getDescricao());
        preparedStatement.setInt(4, produto.getCodigoFornecedor());
        preparedStatement.setInt(5, produto.getCategoria());
        preparedStatement.setDouble(6, produto.getPrecocompra());
        preparedStatement.setDouble(7, produto.getPrecovenda());
        preparedStatement.setInt(8, produto.getEstoque());
        preparedStatement.setInt(9, produto.getCodigo());
        
        preparedStatement.executeUpdate();
        preparedStatement.close();
    } catch (SQLException ex) {
        System.out.println("Erro ao atualizar produto");
        throw new Exception("Erro ao atualizar produto", ex);
    }

    return produto;
}
 
Example 15
Project: redesocial   File: UsuarioDAO.java   View Source Code Vote up 5 votes
/**
* Método responsável pela inserção de um objeto no banco de dados na tabela usuários
* @param dto objeto com os dados de usuário já preenchido
* @throws Exception
*/
@Override
public void inserir(Usuario dto) throws Exception {
    Connection conexao = getConexao();
    
    PreparedStatement pstmt = conexao.prepareStatement("insert into usuarios(nome, email, telefone, senha, data_nascimento, sexo, data_cadastro, status, foto, cidade) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
    
    pstmt.setString(1, dto.getNome());
    pstmt.setString(2, dto.getEmail());
    pstmt.setString(3, dto.getTelefone());
    pstmt.setString(4, dto.getSenha());
    pstmt.setDate(5, new java.sql.Date(dto.getDataNascimento().getTime()));
    pstmt.setString(6, String.valueOf(dto.getSexo().getId()));
    pstmt.setDate(7, new java.sql.Date(dto.getDataCadastro().getTime()));
    pstmt.setBoolean(8, dto.getStatus());
    
    if (dto.getFoto() != null){
        pstmt.setInt(9, dto.getFoto().getId());
    } else {
        pstmt.setNull(9, Types.BLOB);
    }
    
    
    pstmt.setInt(10, dto.getCidade().getId()); 
   
    /**
  * executa uma inserção
  */
    pstmt.executeUpdate();
    
    dto.setId(getId(pstmt));
}
 
Example 16
Project: parabuild-ci   File: TestCacheSize.java   View Source Code Vote up 5 votes
void selectID() {

        StopWatch        sw        = new StopWatch();
        java.util.Random randomgen = new java.util.Random();
        int              i         = 0;
        boolean          slow      = false;

        try {
            PreparedStatement ps = cConnection.prepareStatement(
                "SELECT firstname,lastname,zip,filler FROM test WHERE id = ?");

            for (i = 0; i < smallops; i++) {
                ps.setInt(1, nextIntRandom(randomgen, bigrows - 1));
                ps.execute();

                if (reportProgress && (i + 1) % 10000 == 0
                        || (slow && (i + 1) % 100 == 0)) {
                    System.out.println("Select " + (i + 1) + " : "
                                       + (sw.elapsedTime() + 1));
                }
            }

            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        long time = sw.elapsedTime();
        long rate = ((long) i * 1000) / (time + 1);

        storeResult("select random id", i, time, rate);
        System.out.println("select time for random id " + i + " rows  -- "
                           + time + " ms -- " + rate + " tps");
    }
 
Example 17
Project: scorekeeperfrontend   File: PostgresqlDatabase.java   View Source Code Vote up 5 votes
void bindParam(PreparedStatement p, List<Object> args) throws SQLException
{
    if (args == null)
        return;

    for (int ii = 0; ii < args.size(); ii++)
    {
        Object v = args.get(ii);
        if (v == null) {
            p.setNull(ii+1, java.sql.Types.NULL);
        } else if (v instanceof Integer) {
            p.setInt(ii+1, (Integer)v);
        } else if (v instanceof Long) {
            p.setLong(ii+1, (Long)v);
        } else if (v instanceof Double) {
            p.setDouble(ii+1, (Double)v);
        } else if (v instanceof String) {
            p.setString(ii+1, (String)v);
        } else if (v instanceof Boolean) {
            p.setBoolean(ii+1, (Boolean)v);
        } else if (v instanceof UUID) {
            p.setObject(ii+1, v);
        } else if (v instanceof JSONObject) {
            PGobject pgo = new PGobject();
            pgo.setType("json");
            pgo.setValue(((JSONObject)v).toJSONString());
            p.setObject(ii+1, pgo);
        } else if (v instanceof Timestamp) {
            p.setTimestamp(ii+1, (Timestamp)v);
        } else {
            throw new SQLException("unexpected param type: " + v.getClass());
        }
    }
}
 
Example 18
Project: LojaDeInstrumentosMusicais   File: ProdutoDAO.java   View Source Code Vote up 5 votes
public Produto encontrarProdutoCodigo(int codigo, int codigoempresa){//retorna um item
    Produto produto = new Produto();
    System.out.println("Buscando produto na base de dados...");
    String query = "";
    query = "SELECT * FROM produtos WHERE codigo=? and codigoempresa=?";//addicionar o % %

    
    try {
        PreparedStatement preparedStatement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        
        preparedStatement.setInt(1,codigo);
        preparedStatement.setInt(2,codigoempresa);
        
        ResultSet rs = preparedStatement.executeQuery();
        
        while (rs.next()){
            produto.setCodigo(rs.getInt(1));
            produto.setCodigoempresa(rs.getInt(2));
            produto.setNome(rs.getString(3));
            produto.setDescricao(rs.getString(4));
            produto.setCodigoFornecedor(rs.getInt(5));
            produto.setCategoria(rs.getInt(6));
            produto.setPrecocompra(rs.getDouble(7));
            produto.setPrecovenda(rs.getDouble(8));
            produto.setEstoque(rs.getInt(9));
        }
        
        System.out.println("Busca efetuada com sucesso");
    } catch (SQLException ex) {
        System.out.println("Erro ao buscar produto"+ex);
    }        
    return produto;

}
 
Example 19
Project: HTAPBench   File: StockLevel.java   View Source Code Vote up 4 votes
private void stockLevelTransaction(int w_id, int d_id, int threshold, Connection conn,TPCCWorker w)
		throws SQLException {
	int o_id = 0;
	// XXX int i_id = 0;
	int stock_count = 0;

                      PreparedStatement stockGetDistOrderId = getPreparedStatement(conn, stockGetDistOrderIdSQL);
	stockGetDistOrderId.setInt(1, w_id);
	stockGetDistOrderId.setInt(2, d_id);
	ResultSet rs = stockGetDistOrderId.executeQuery();

	if (!rs.next())
		throw new RuntimeException("D_W_ID="+ w_id +" D_ID="+ d_id+" not found!");
	o_id = rs.getInt("D_NEXT_O_ID");
	rs.close();
	rs = null;
                      PreparedStatement stockGetCountStock = getPreparedStatement(conn, stockGetCountStockSQL);

	stockGetCountStock.setInt(1, w_id);
	stockGetCountStock.setInt(2, d_id);
	stockGetCountStock.setInt(3, o_id);
	stockGetCountStock.setInt(4, o_id);
	stockGetCountStock.setInt(5, w_id);
	stockGetCountStock.setInt(6, threshold);
	rs = stockGetCountStock.executeQuery();

	if (!rs.next())
		throw new RuntimeException("OL_W_ID="+w_id +" OL_D_ID="+d_id+" OL_O_ID="+o_id+" not found!");
	stock_count = rs.getInt("STOCK_COUNT");

	conn.commit();

	rs.close();
	rs = null;

	StringBuilder terminalMessage = new StringBuilder();
	terminalMessage
			.append("\n+-------------------------- STOCK-LEVEL --------------------------+");
	terminalMessage.append("\n Warehouse: ");
	terminalMessage.append(w_id);
	terminalMessage.append("\n District:  ");
	terminalMessage.append(d_id);
	terminalMessage.append("\n\n Stock Level Threshold: ");
	terminalMessage.append(threshold);
	terminalMessage.append("\n Low Stock Count:       ");
	terminalMessage.append(stock_count);
	terminalMessage
			.append("\n+-----------------------------------------------------------------+\n\n");
	if(LOG.isTraceEnabled())LOG.trace(terminalMessage.toString());
}
 
Example 20
Project: parabuild-ci   File: TestSql.java   View Source Code Vote up 2 votes
/**
 * Fix for bug #1201135
 */
public void testBinds() {

    try {
        PreparedStatement pstmt =
            connection.prepareStatement("drop table test if exists");

        pstmt.execute();

        pstmt =
            connection.prepareStatement("create table test (id integer)");

        pstmt.execute();

        pstmt =
            connection.prepareStatement("insert into test values (10)");

        pstmt.execute();

        pstmt =
            connection.prepareStatement("insert into test values (20)");

        pstmt.execute();

        pstmt = connection.prepareStatement(
            "select count(*) from test where ? is null");

        pstmt.setString(1, "hello");

        ResultSet rs = pstmt.executeQuery();

        rs.next();

        int count = rs.getInt(1);

        assertEquals(0, count);

        pstmt =
            connection.prepareStatement("select limit ? 1  id from test");

        pstmt.setInt(1, 0);

        rs = pstmt.executeQuery();

        rs.next();

        count = rs.getInt(1);

        assertEquals(10, count);
        pstmt.setInt(1, 1);

        rs = pstmt.executeQuery();

        rs.next();

        count = rs.getInt(1);

        assertEquals(20, count);
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("TestSql.testBinds() error: "
                           + e.getMessage());
    }
}