java如何将图片类型的数据存入mysql 数据库

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();


}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值