我正在使用 postgres PostgreSQL 9.1 并有一个带有列 bytea 数据类型的表。当尝试插入图像时,它能够将图像插入到表中,表的架构如下:
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
请澄清问题的根本原因是什么。在此先感
谢森蒂尔