shenzhang 发表于 2016-10-23 01:44:28

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

OSWindowsXPMyEclipse7.0mysql5.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( StringfromFileName,StringtoFileName) {
Connection conn = this.getConn();
PreparedStatement ps;
try {
ps = conn.prepareStatement("insert intophoto( 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    voidgetAll(){
String sql = "select*from   photo";
Connection conn = this.getConn();
PreparedStatement ps;
try {
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
intj=0;
while (rs.next()) {
InputStream ins = null;
OutputStream out = null;
j++;
System.out.println(rs.getInt(1) + "\t" + rs.getString(2));
Blobblob= rs.getBlob("myphoto");
ins = blob.getBinaryStream();
Filef = new File(rs.getString(2));
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buf = new byte;
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();
}
}
publicvoidget(int id)
{
String sql = "select*from   photowhereid= ?";
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;
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, FilenewFile)
{
try {
String sql = "updatephotosetmyphoto=?whereid="+id;
Connection conn = this.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
InputStreamin = 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>();
privatestatic 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(StringfromName,   StringtoName ) {
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;
int i = 0;
while ((i = in.read(buf)) != -1)
{
out.write(buf);
}
session.close();
}catch(IOExceptione)
{
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void getAll()throwsIOException, 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;
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
{
PhotoDaopd=new PhotoDao();
//pd.save("b.jpg","bbbbbb.jpg");
pd.getAll();

}
}
页: [1]
查看完整版本: java如何将图片类型的数据存入mysql 数据库