How do I put autoincrement

1

In the database I can only insert if I add a code, but I want it to be auto increment, in the database I use postgre and declare the code as serial

String sql = "INSERT INTO tbl_cliente(codigo,nome, cpf, telefone, endereco, sexo, pagamento, modelo, ano, marca, custoconcerto) VALUES "
            + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    try {
        pst = conecta.prepareStatement(sql);
        pst.setInt(1,"Aqui é o autoincrement");
    
asked by anonymous 04.06.2016 / 16:18

2 answers

0

A self-increment column in PostgreSQL works from the default value, not a special value. Just omit it:

CREATE TABLE tbl_cliente (
    codigo SERIAL,
    nome TEXT
);

INSERT INTO tbl_cliente (nome) VALUES ('Diego');

Or use the keyword DEFAULT instead of a value:

INSERT INTO tbl_cliente (codigo, nome) VALUES (DEFAULT, 'Diego');

Columns that do not appear in the INSERT list are set to their default values. In the case of a column SERIAL or BIGSERIAL , this value is the next number in its sequence.

In Java it's the same as in SQL: it simply does not include any values for the column:

String sql = "INSERT INTO tbl_cliente (nome) VALUES (?)"
// ou
String sql = "INSERT INTO tbl_cliente (codigo, nome) VALUES (DEFAULT, ?)"
PreparedStatement pst = algo.prepareStatement(sql);
pst.setString(1, oNome);

More information is available in the PostgreSQL documentation: INSERT , default values , SERIAL .

    
04.06.2016 / 18:14
0

My friend, the problem is not the command but the table, to leave the field auto_increment is necessary to create a sequence. Just like other DBMS.

It would look something like this to create the table, and when using the command does not need to enter the field code.

CREATE TABLE tbl_cliente (codigo integer NOT NULL, "demais campos");
CREATE SEQUENCE seq_codigo
INCREMENT 1
MINVALUE 1
MAXVALUE 9999
START 1
CACHE 1;

ALTER TABLE tbl_cliente ALTER COLUMN codigo SET DEFAULT NEXTVAL("seq_codigo"::regclass);
    
04.06.2016 / 21:21