本文主要介绍:
1.如何通过JDBC把图片保存在数据库中(1)
2.如何通过JDBC把已经存在数据库的图片读取出来,再通过IO流写到指定位置(2)
注:图片如此,音频,视频亦是如此!
1.如何通过JDBC把图片保存在数据库中:
在之前的“JDBC五大步骤”中有写到第三步是发送诉求,用的是Statement类:
// Statement statement = connection.createStatement();
// statement.executeUpdate("insert into imgdemo values()")
那么我们values()里面要写什么呢?我们是要写一串二进制数字吗?
显然不科学,所以我们需要用另一个类PreparedStatement,这个类的好处在于他的values()里面可以使用”?“来占位,之后在设置这个?的值即可。
一下是全部代码:
package a1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Administrator
* 把图片保存到数据库中
*
*/
public class Test06 {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;DatabaseName = tongjunchao";
Connection connection = DriverManager.getConnection(url,"sa","123");
// Statement statement = connection.createStatement();
// statement.executeUpdate("insert into imgdemo values()")
File file = new File("e:\\a1.jpg");
byte[] b = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(b);
String sql = "insert into imgdemo values(?,?)";
PreparedStatement pStatement = connection.prepareStatement(sql);//这个类就是很高级也!
pStatement.setInt(1, 1);//设置第一个问号
pStatement.setBytes(2, b);
pStatement.execute();//执行
pStatement.close();
connection.close();
System.out.println("ok");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据库:
create table imgdemo(
id int primary key,
img image
)
数据库的结果:
id img
1 0xFFD8FFE154..............
2.请看下一篇,(^__^) 嘻嘻