设为首页 收藏本站
查看: 351|回复: 0

[经验分享] java如何将图片类型的数据存入mysql 数据库

[复制链接]

尚未签到

发表于 2016-10-23 01:44:28 | 显示全部楼层 |阅读模式
OS  WindowsXP  MyEclipse7.0  mysql5.0
在mysql 建立一张photo 的表
图片类型在mysql 中的列类型是Blob; Java中是java.sql.Blob类型

create table photo(
id int not null auto_increment primary key ,
pname       varchar(30) not null ,
myphoto blob
);

在mysql 中的jdbc

package com.lyx.util;
import java.sql.*;
import java.io.*;
public class MyBlob {
/*
* create table photo( id int not null auto_increment primary key , pname
* varchar(30) not null , myphoto blob );
*/
public Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "791129");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//fromFileName 有保证文件存在
public void add( String  fromFileName,  String  toFileName) {
Connection conn = this.getConn();
PreparedStatement ps;
try {
ps = conn.prepareStatement("insert into  photo( pname , myphoto)  values(?,?)");
ps.setString(1, toFileName);
File file = new File(fromFileName);
InputStream in;
in = new BufferedInputStream(new FileInputStream(file));
ps.setBinaryStream(2, in, (int) file.length());
int count = 0;
count = ps.executeUpdate();
if(count==1)
{
System.out.println("插入数据成功!");
}else
{
System.out.println("插入数据失败!");
}
in.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public    void  getAll(){
String sql = "select  *from   photo";
Connection conn = this.getConn();
PreparedStatement ps;
try {
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int  j=0;
while (rs.next()) {
InputStream ins = null;
OutputStream out = null;
j++;
System.out.println(rs.getInt(1) + "\t" + rs.getString(2));
Blob  blob= rs.getBlob("myphoto");
ins = blob.getBinaryStream();
File  f = new File(rs.getString(2));
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buf = new byte[1024];
int i = 0;
while ((i = ins.read(buf)) != -1) {
out.write(buf);
}
ins.close();
out.close();
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public  void  get(int id)
{
String sql = "select  *from   photo  where  id= ?";
Connection conn = this.getConn();
PreparedStatement ps;
try {
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
File f = null;
InputStream ins = null;
OutputStream out = null;
Blob blob =null;
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2));
blob= rs.getBlob("myphoto");
ins = blob.getBinaryStream();
f = new File(rs.getString(2));
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buf = new byte[1024];
int i = 0;
while ((i = ins.read(buf)) != -1) {
out.write(buf);
}
ins.close();
out.close();
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public      void   update(int id  , File  newFile)
{
try {
String sql = "update  photo  set  myphoto=?  where  id="+id;
Connection conn = this.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
InputStream  in = new BufferedInputStream(new FileInputStream(newFile));
ps.setBinaryStream(1, in, (int) newFile.length());
int   count=0;
count=ps.executeUpdate();
System.out.println(count);
ps.close();
in.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException
{
}

用hibenate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--  
<property name="hbm2ddl.auto">update</property> -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/mydb
</property>
<property name="connection.username">root</property>
<property name="connection.password">791129</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="show_sql">true</property>
<mapping resource="com/h/Photo.hbm.xml" />
</session-factory>
</hibernate-configuration>
  
Photo.hbm.xml  文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.h.Photo" table="photo" >
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="pname" type="java.lang.String">
<column name="pname" length="30" not-null="true" />
</property>
<property name="myphoto" type="java.sql.Blob">
<column name="myphoto" />
</property>
</class>
</hibernate-mapping>


程序文件SessionFactory .java

package com.h.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class SessionFactory {

private static String CONFIG_FILE_LOCATION = "/com/lyx/util/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private  static Configuration configuration = new Configuration();   
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private SessionFactory() {
}

public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}

public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}

public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void setConfigFile(String configFile) {
SessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}

pojo 文件

package com.h;
import java.sql.Blob;
/**
* Photo entity. @author MyEclipse Persistence Tools
*/
@SuppressWarnings("serial")
public class Photo implements java.io.Serializable {

private Integer id;
private String pname;
private Blob myphoto;

public Photo() {
}

public Photo(String pname) {
this.pname = pname;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return this.pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Blob getMyphoto() {
return myphoto;
}

public void setMyphoto(Blob myphoto) {
this.myphoto = myphoto;
}

}


session操作文件

package com.h;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;
import com.h.util.SessionFactory;
import org.hibernate.Hibernate;
import org.hibernate.Session;
/**
* @author 李亚希 版权所有 :天豪工作室 2009-9-21
*/
public class PhotoDao {
public PhotoDao() {
}
/**
* @param fromName  将要存入数据库的图片文件名
* @param toName    表中的列---定义的新的图片名
*/
public void save(String  fromName,   String  toName ) {
try {
Session session = SessionFactory.getSession();
File ff = new File(fromName);
FileInputStream fis = new FileInputStream(ff);
Blob bbb = Hibernate.createBlob(fis);
Photo pp = new Photo();
pp.setPname(toName);
pp.setMyphoto(bbb);
session.save(pp);
System.out.println(pp.getId());
session.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param id    获取行数据的id值
* @param outputFileName  输出的文件名
*/
public void getById(int id) {
try{
Session session = SessionFactory.getSession();
Photo p = (Photo) session.get(Photo.class, id);
System.out.println(p.getId() + "\t" + p.getPname());
Blob b = p.getMyphoto();
InputStream in = b.getBinaryStream();
File f = null;
OutputStream out = null;
f = new File(p.getPname());
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buf = new byte[1024];
int i = 0;
while ((i = in.read(buf)) != -1)
{
out.write(buf);
}
session.close();
}catch(IOException  e)
{
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void getAll()  throws  IOException, SQLException  
{
Session session = SessionFactory.getSession();
List ps = session.createQuery("from   Photo").list();
System.out.println("ps.size=====" + ps.size());
if (ps.size() > 0) {
for (int i = 0; i < ps.size(); i++) {
InputStream in = null;
OutputStream out = null;
Blob b = null;
File f = null;
Photo p = (Photo) ps.get(i);
System.out.println(p.getId() + "\t" + p.getPname());
b = p.getMyphoto();
in = b.getBinaryStream();
f = new File(p.getPname());
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buf = new byte[1024];
int j = 0;
while ((j = in.read(buf)) != -1) {
out.write(buf);
}
in.close();
out.close();
}
}
session.close();
}
public static void main(String[] args) throws SQLException, IOException
{
PhotoDao  pd=new PhotoDao();
//pd.save("b.jpg","bbbbbb.jpg");
pd.getAll();

}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-289836-1-1.html 上篇帖子: MySQL中show 句法得到表列及整个库的详细信息(精品珍藏) 下篇帖子: MapXtreme-4.8.0从mysql中获取经纬度绘制层的问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表