楼上的,你那是存入图片,不是取得图片 InputStream in = rs.getBinaryStream(1); // Some database systems may not be able to tell us // how big the data actuall is. Let's read all of it // into a buffer. ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte b[] = new byte[1024]; while (true) { int bytes = in.read(b); // If there was nothing read, get out of loop if (bytes == -1) { break; } // Write the buffer to our byte array baos.write(b, 0, bytes); } // Now we have the entire image in the buffer. Get // the length and write it to the output stream b = baos.toByteArray();//二进制图片文件保存到b
InputStream in = rs.getBinaryStream(1); 这里的参数根据你的查询获得的图片字段的列数,从1开始(我这里就select picture from...,所以参数是1) rs是ResultSet的一个对象
import java.sql.*;
import java.io.*;public class WriteDB {
public static void main(String[] args) {
Connection conn=null;
String driver="com.mysql.jdbc.Driver";//驱动
String url="jdbc:mysql://127.0.0.1/test?useUnicode=true;characterEncoding=8859_1";// 数据库联接 try{
Class.forName(driver).newInstance();
conn=DriverManager.getConnection(url,"root","");
File file=new File(args[0]);
FileInputStream fis=new FileInputStream(file);
PreparedStatement pstmt=conn.prepareStatement(
"insert into picture(picture) values(?)");
int bytes=(int)file.length();
System.out.println(bytes);
pstmt.setBinaryStream(1,fis,bytes);//1为插入的参数1,2fileInStream为插入的数据,bytes为字节长度
pstmt.executeUpdate(); conn.close();
fis.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
InputStream in = rs.getBinaryStream(1); // Some database systems may not be able to tell us
// how big the data actuall is. Let's read all of it
// into a buffer.
ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte b[] = new byte[1024];
while (true) {
int bytes = in.read(b); // If there was nothing read, get out of loop
if (bytes == -1) {
break;
} // Write the buffer to our byte array
baos.write(b, 0, bytes);
} // Now we have the entire image in the buffer. Get
// the length and write it to the output stream
b = baos.toByteArray();//二进制图片文件保存到b
这里的参数根据你的查询获得的图片字段的列数,从1开始(我这里就select picture from...,所以参数是1)
rs是ResultSet的一个对象