Tuesday, May 8, 2012

Comparing a byte value with a bytea column in postgresql

I am using PostgreSQL as my database and java servlet to communicate with PostgreSQL. My application requires that I fetch data from database for a matching input file. All the files are stored in the database in a bytea column. This is my code:



String checkdb="select * from key where certificate = '"+c+"';";
Statement stcheck=conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet newrs=stcheck.executeQuery(checkdb);
newrs.last();
int rowcount=newrs.getRow();
if(rowcount!=0)
throw new ArithmeticException();


where certificate is the name of the column containing the bytea data and c (uploaded) is a certificate in byte[] form. So here I am checking if the uploaded certificate is already present in the database. If it is present then I am throwing an exception.



But the problem is uploading the same certificate multiple times is not throwing an exception is working as if the two certificates are different.



Am I comparing the byte values correctly. What should I do to correct this?

EDIT

I tried setting the certificate column as the primary key. But still the certificate gets inserted into the database. How could this happen? The internal comparison also fails for some reason.

EDIT

I tried retrieving a ile and converted it to string :



InputStream input13 = retrs.getBinaryStream("certificate");
ByteArrayOutputStream output13 = new ByteArrayOutputStream();
byte buf[]=new byte[1024];
int len;
IOUtils.copy(input13, output13);
input13.close();
byte[] retvalue=output13.toByteArray();
String s1=new String(retvalue);

String s2=new String(c);
System.out.println("in--------------"+s2);


System.out.println("out----------------"+s1);



retrs is the result set containing the just stored certificate. c is the input certificate in byte[]. The out put that I get is:



19:05:43,156 INFO  [STDOUT] in-------------------BEGIN CERTIFICATE-----
MIICIjCCAYsCAQMwDQYJKoZIhvcNAQEFBQAwYTELMAkGA1UEBhMCYXMxCzAJBgNV
BAgMAmFzMQswCQYDVQQHDAJhczELMAkGA1UECgwCYXMxCzAJBgNVBAsMAmFzMQsw
CQYDVQQDDAJjYTERMA8GCSqGSIb3DQEJARYCYXMwHhcNMTIwNDEwMDY0ODQ3WhcN
MTMwNDEwMDY0ODQ3WjBSMQswCQYDVQQGEwJhczELMAkGA1UECBMCYXMxCzAJBgNV
BAcTAmFzMQswCQYDVQQKEwJhczELMAkGA1UECxMCYXMxDzANBgNVBAMTBmNsaWVu
dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsfJq9TVgTLqz84nuWpDm+dvI
do2HIWoHkmEPNowK4xn1+qWUPCy30aASWI92YMtE6njtQGyZBYij0iTAxldDktqd
bMdpKAONDlSv71rn+fZPuyenbBFYZexybNVsRMFzTD/F/hiPPXT7E1j9CrgIMxVz
ScZeNATh/dPLwuNQ0dsCAwEAATANBgkqhkiG9w0BAQUFAAOBgQDDUyeIWlKaMMkM
8VRGuDJyKFC8miQfmul6zE4+6RTswHKjcUoje2vhTQgV+GBfqx8ai+ziujx8CeyR
eJWcb1G8gg+LMUNDcTOlXTeBG9L2c/gMOEu7BEjtpojSYmFyEvJEQ5Yep44HKZZb
FSPFVNxGiXBhNxtKQdAu6/smQ/eBNg==
-----END CERTIFICATE-----
19:05:43,156 INFO [STDOUT] out----------------[B@17f8b39




No comments:

Post a Comment