create table image (id int primary key auto_increment , name varchar(30) COMMENT '名称', content mediumblob COMMENT '图片');
package jdbc_imagetest;
import java.io.*;
import java.sql.*;
/**
* 将本地文件的图片传到数据库的test的image表中并下载到本机桌面
*/
public class Test1 {
private static String url="jdbc:mysql://localhost:3306/test";
private static String user="root";
private static String password="123456";
private static Connection con;
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url,user,password);
shangchuan();
xiazai();
}
//添加图片到数据库test4的file表
public static void shangchuan() throws Exception{
String sql="insert into image(name,content) values(?,?)";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setString(1, "美女.jpg");
InputStream is=null;
is=new FileInputStream("D:\Pictures\3.jpg");
ptmt.setBinaryStream(2, is,is.available());
//方法说明:PreparedStatement.setBinaryStream(int parameterIndex, InputStream x, int length)
ptmt.execute();
System.out.println("图片添加成功!");
}
//从数据库中把图片下载至桌面
public static void xiazai() throws Exception{
String sql="select content from image where id=3";//在我这里3.jpg是第三张图片
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);//将查询结果给rs
if(rs.next()){
InputStream is=rs.getBinaryStream("fcontent");
//.getBinaryStream():a Java input stream that delivers the database column value as a stream of uninterpreted bytes
FileOutputStream fos=new FileOutputStream("C:\Users\Desktop\美女.jpg");
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);//将数据库的图片写出
}
System.out.println("下载成功!已下载至桌面,请查看");
}else{
System.out.println("图片不存在!");
}
con.close();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有