我正在使用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
请澄清可能是问题的根本原因。 提前谢谢你 塞特希
答案 0 :(得分:1)
fis.read()返回读取的字节数,以获取数据初始化字节数组(在我的代码中,这是 b )到文件长度并调用读取如下:
File file = new File("C:\\pics\\viticcio.jpg");
byte[] b = new bye[file.length()];
fis.read(b);
pstmt.setBytes(4, b);
PreparedStatement默认为只读。要将其设置为可更新的初始化,如下所示:
PreparedStatement pstmt = c.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);