import java.sql.*;
import java.io.*;
public class Photo{
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
Connection conn=DriverManager.getConnection("jdbc:mysql://192.168.24.75:3306/photoserver?useUnicode=true&characterEncoding=utf-8","root","123");//建立数据库链接
// File file=new File("D://xx.jpg");//指定入库的文件
String path=null;String path2=null;String path3=null;
for(int i =1; i <= 5; i++)
{
for(int j =1; j <=4; j++)
{
//第一种路径:path = (new StringBuilder()).append("E:\\map1\\hsxy\\").append("m").append(i).append("-").append(j).append("").append(".jpg").toString();
path=("F:\\photo18\\m");
path2=(i+"-"+j);
path3=(".jpg");
System.out.print("读取图片:");
File file=new File(path+path2+path3);
FileInputStream fis=new FileInputStream(file);//创建输入流对象这里可以将fis想象成一个管道 这个管道架在file中存的路径所对应的图片上 将这个图片化成的二进制数据装入管道fis
PreparedStatement ps=conn.prepareStatement("insert into photo18 values(?,?)"); //通过实例对象cn将SQL语句存入 PS中带入SQL数据库中
ps.setBinaryStream(1,fis,(int)file.length());
ps.setString(2,file.getName());
ps.executeUpdate();//执行该数据库语句最终将图片分解成二进制数据放入表中的PHOTO字段
System.out.print(path+path2+path3);
System.out.println("图片入库成功");
ps.close();
fis.close();}}
conn.close();
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/**建库信息**/
/*create database 表名 ;
/**建表信息**/
/*
use 表名;
create table image(image longblob,name char(30));
*/
下载:
public class Test {
static String dbURL = "jdbc:mysql://localhost:3306/photoserver";
static String userID = "root";
static String passwd = "123";
public static void main(String[] args)throws Exception {
File f = new File(".\\"+File.separator+"photo") ;// 实例化File类的对象
f.mkdir() ; // 创建文件夹
Class.forName("com.mysql.jdbc.Driver");
Connection conn=(Connection) DriverManager.getConnection(dbURL, userID, passwd);
conn.setAutoCommit(false);
String sql2 = "SELECT image,name FROM image ";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
ResultSet resultSet = stmt2.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString(2);
String description = resultSet.getString(1);
File image2 = new File("photo/" + name);
FileOutputStream fos = new FileOutputStream(image2);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(1); /*read(byte[] b),从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。write(byte[] b),
将 b.length 个字节从指定的 byte 数组写入此输出流。 */
System.out.println("成功将:"+name+":写入指定文件夹下");
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
conn.close();
}
}
/**建库信息**/
/*create database 表名 ;
/**建表信息**/
/*
use 表名;
create table image(image longblob,name char(30));
*/