黑马程序员技术交流社区
标题:
数据库
[打印本页]
作者:
wangshuying
时间:
2014-11-16 15:20
标题:
数据库
mysql数据库中,Blob(二进制数据类型)怎么用
作者:
zhappy
时间:
2014-11-18 19:40
存图片或者附件
作者:
sugar
时间:
2014-11-18 22:12
import java.sql.*;
import java.io.*;
public class binarydata {
public static void main(String[] args) {
// TODO Auto-generated method stub
read();
//create();
}
public static void create()
{
Connection ct=null;
PreparedStatement ps=null;
ResultSet rs=null;
try
{
ct=JDBCUtils.getConnection();
String sql="insert into picture(picture)values(?)";
ps=ct.prepareStatement(sql);
InputStream in=new BufferedInputStream(new FileInputStream(new File("1.png")));
ps.setBinaryStream(1, in);
int i=ps.executeUpdate();
System.out.println("i="+i);
in.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
JDBCUtils.free(rs, ps, ct);
}
}
public static void read()
{
Connection ct=null;
PreparedStatement ps=null;
ResultSet rs=null;
try
{
ct=JDBCUtils.getConnection();
String sql="select picture from picture";
ps=ct.prepareStatement(sql);
rs=ps.executeQuery();
int m=0;
while(rs.next())
{
InputStream in=rs.getBinaryStream("picture");
OutputStream out=new BufferedOutputStream(new FileOutputStream(new File("D://"+(m++)+".png")));
byte[] buf=new byte[1024];
int i=0;
while((i=in.read(buf))!=-1)
{
out.write(buf,0,i);
}
in.close();
out.close();
}
}catch(Exception e)
{
e.printStackTrace();
}finally
{
JDBCUtils.free(rs, ps, ct);
}
}
}
复制代码
工具类:
import java.sql.*;
public class JDBCUtils {
private static String url="jdbc:mysql://localhost:3306/user";
private static String user="root";
private static String password="root";
private JDBCUtils(){}
static
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException
{
return DriverManager.getConnection(url,user,password);
}
public static void free(ResultSet rs,Statement st,Connection ct)
{
try
{
if(rs!=null)
rs.close();
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(st!=null)
st.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
if(ct!=null)
try {
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2