How to store byte from Java into a bytea in PostgreSQL?

Renato Pereira picture Renato Pereira · Jan 22, 2014 · Viewed 20.3k times · Source

I am getting a problem when I try to insert a variable of type "byte" in Java into a variable of type "bytea" in PostgreSQL.

This is my table in postgresql:

CREATE TABLE mesa (
   id_mesa              serial PRIMARY KEY,
   tag                  varchar(50),
   modelo               varchar(50),
   menor_complemento    smallint NOT NULL,
   peso_min             smallint NOT NULL,
   peso_max             smallint NOT NULL,
   som                  bytea NOT NULL,
   rotina               bytea NOT NULL,
   address64bits        bytea NOT NULL UNIQUE
);

my code in Java is the following:

private Mesa mesa;
//construtor
public MesaDAO (Mesa mesa) {
    this.mesa = mesa;
}
(...)
String stm = "INSERT INTO mesa(tag, modelo, menor_complemento, peso_min, "
            + "peso_max, som, rotina, address64bits) "
            + "VALUES(?,?,?,?,?,?,?,?)";
    try {
        pst = con.prepareStatement(stm);
        pst.setString(1, mesa.getTag());
        pst.setString(2, mesa.getModelo());
        pst.setInt(3, mesa.getMenorComplemento());
        pst.setInt(4, mesa.getPesoMin());
        pst.setInt(5, mesa.getPesoMax());
        pst.setByte(6, mesa.getSom());
        pst.setByte(7, mesa.getRotina());
        pst.setBytes(8, mesa.getAddress64Bits());
        pst.executeUpdate();
        (...)

The mesa types are:

public class Mesa{
  private Integer idMesa;
  private String tag;
  private String modelo;
  private Integer menorComplemento;
  private Integer pesoMin;
  private Integer pesoMax;
  private byte som;
  private byte rotina;
  private byte[] address64Bits;
  (...)
}

Then, when I try to insert something it throws a PSQLException stating that the column "som" is a "bytea" but the expression is a "smallint". I also think it gonna have the same SQLException on the following two lines after that one.

So I don't know how to fix that, if someone could help me I will be glad!

Thank you in advance,

EDIT:

Thanks guys for helping me, I will provide the solution here: change the variable "som" and "rotina" to "byte[]" type and then use pst.getBytes(...) instead of pst.getByte(...).

Clarifying:

I am using XBee (API mode), so I need to send the byte value through the port serial. So I was just verifying if what I am getting from the database is the same value of that one I inserted there. In conclusion, I want to know how to recover the bytes from database to send them through the serial port.

Answer

Gilberto picture Gilberto · Apr 6, 2014

Code Java by PostgreSQL

pst.setBinaryStream(6, mesa.getSom());
pst.setBinaryStream(7, mesa.getRotina());
pst.setBinaryStream(8, mesa.getAddress64Bits());`