我正在使用postgres PostgreSQL 9.1,並有一個列bytea數據類型的表。當試圖插入一個圖像,它是能夠將圖像插入到表中,表的模式如下:postgres中的圖像大小不匹配9.1
CREATE TABLE emp
(
uname character varying(100) NOT NULL,
pass character varying(100) NOT NULL,
name character varying(100) NOT NULL,
dob date,
country character varying(20),
region character varying(20),
description character varying(3000),
role character varying(100),
photo bytea,
CONSTRAINT emp_pkey PRIMARY KEY (uname)
)
WITH (
OIDS=FALSE
);
ALTER TABLE emp
OWNER TO postgres;
示例Java代碼如下:
package com.q4;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.*;
public class DataTest {
public void insert() throws Exception
{
Connection c = ConnectionHelper.getConnection();
FileInputStream fis = new FileInputStream("C:\\pics\\viticcio.jpg");
int counter = 0;
String sql ="insert into emp(uname, pass,name,photo) values (?,?,?,?)";
PreparedStatement pstmt = c.prepareStatement(sql);
pstmt.setString(1, "Senthil1");
pstmt.setString(2, "Password");
pstmt.setString(3, "Senthil1");
//pstmt.setBlob(4, fis);
while(fis.read() != -1) counter++;
byte[] b= new byte[counter];
fis.close();
fis = new FileInputStream("C:\\pics\\viticcio.jpg");
for(int i = 0;i<counter;i++)
{
b[i] = (byte)fis.read();
// System.out.print(b[i]);
}
System.out.println("Input File Size : " + counter); //Output 1
System.out.println(counter);
pstmt.setBytes(4, b);
// pstmt.setBlob(4, fis, counter);
pstmt.executeUpdate();
System.out.println("Successfully insertted ...");
}
public void select() throws Exception
{
String sql = "select * from emp where uname = ?";
Connection c = ConnectionHelper.getConnection();
PreparedStatement pstmt = c.prepareStatement(sql);
pstmt.setString(1, "Senthil1");
ResultSet set = pstmt.executeQuery();
if(set.next())
{
FileOutputStream fos = new FileOutputStream("C:\\test.jpg");
byte[] a = set.getBytes("photo");
System.out.println("Output Filesize : "+a.length); //Output 2
for(int i = 0; i <a.length;i++)
{
fos.write((byte)a[i]);
// System.out.print((byte)a[i]);
fos.flush();
}
fos.close();
}
pstmt.close();
c.close();
}
public static void main(String[]s) throws Exception
{
new DataTest().insert();
new DataTest().select();
}
}
的我在下面給出了運行這個程序的輸出,並且文件test.jpg在C:\中創建,但是這個文件的大小是讀取文件大小的兩倍。
Input File Size : 6455
6455
Successfully insertted ...
SELECT ......... 12909
請說明可能是問題的根本原因。 預先感謝
塞特希
謝謝您的回答,問題解決了。我正在使用postgres 9.1並使用驅動程序postgres 8.2。當我替換postgres 9.1的驅動程序時,解決了問題。 – user1503117