package chp19;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Image_DataBase {
public static void main(String[] args) {
// 生成测试类
try {
File file = new File("D:/abc/PIC3.bmp"); // 将保存的图片生成文件对象
if (Image_byte(null, file)) // 如果文件成功读入byte数组则返回true。否者返回false
System.out.print("ture");
else
System.out.print("False");
} catch (Exception e) {
System.out.println("图像生成文件对象失败 " + e.getMessage());
}
}
public static boolean Image_byte(String sqlstr, File file) { // 将图像文件转换成byte[]
try {
// 将文件对象流化,并在内存生成文件大小的缓存区
FileInputStream fin = new FileInputStream(file);
// 创建字节缓存区,并分文件大小空间
ByteBuffer nbf = ByteBuffer.allocate((int) file.length());
byte[] array = new byte[1024];
int offset = 0, length = 0;
// 存放字节流
while ((length = fin.read(array)) > 0) {
if (length != 1024)
nbf.put(array, 0, length);
else
nbf.put(array);
offset += length;
}
// 关闭文件流
fin.close();
byte[] content = nbf.array();
System.out.println(content.length);
return LoadImage(sqlstr, content);
} catch (Exception e) {
System.out.println("图像转换成byte数组失败 " + e.getMessage());
}
return false;
}
private static boolean LoadImage(String sqlstr, byte[] in) {
boolean flag = false;
if (sqlstr == null) {
sqlstr = "select * from image";
try {
// 获取连接,生成记录集
Connection con = getConnection();
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sqlstr);
// 如果记录存在则更新记录
if (rs.next()) {
rs.updateBytes(3, in);
rs.updateRow();
System.out.println(" updateRow");
// 否则插入新纪录
} else {
rs.moveToInsertRow();
rs.updateString(2, "01");
rs.updateBytes(3, in);
rs.insertRow();
System.out.println("insertRow");
}
rs.close();
flag = true;
// 处理异常
} catch (Exception e) {
System.out.println("图像存入数据库失败 " + e.getMessage());
}
// 返回标签
return flag;
}
return flag;
}
public static Connection getConnection() { // 连接数组库
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // 加载Mysql数据驱动
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/myuser", "root", "root"); // 创建数据连接
} catch (Exception e) {
System.out.println("数据库连接失败 " + e.getMessage());
}
return con;
}
}