java mysql儲存和讀取檔案

不設限發表於2011-12-11

儲存圖片


import java.io.File;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SavePic {


public static void main(String[] args) throws Exception {
SavePic sp=new SavePic();
PreparedStatement pstmt=null;
FileInputStream fis=null;
Connection conn=sp.getConn();
String sql="insert into pic(filename,content) values(?,?)";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1,"p2");
File file=new File("src\\chapter18\\pic\\yy.jpg");
fis=new FileInputStream(file);
//這三個引數都需要提供,否則就會報錯
pstmt.setBinaryStream(2, fis,(int)file.length());
pstmt.executeUpdate();
fis.close();
pstmt.close();
conn.close();
}

public Connection getConn() {
Connection conn = null;
String url = "jdbc:mysql://localhost/dandan?user=root&password=dada&characterEncoding=utf-8";
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

}


獲取圖片:


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;




public class GetPic {


public static void main(String[] args) throws Exception {
GetPic gp=new GetPic();
ResultSet rs=null;
PreparedStatement ps=null;
Connection conn=gp.getConn();
FileOutputStream fos=null;
String sql="select * from pic where filename=?";
ps=conn.prepareStatement(sql);
ps.setString(1, "p1");
rs=ps.executeQuery();
//把指標向下移動
rs.next();
File file=new File("src/chapter18/pic/gg.jpg");
if(!file.exists()) file.createNewFile();
fos=new FileOutputStream(file);
InputStream is=rs.getBinaryStream(2);
int len=0;
byte[] b=new byte[1024];
while((len=is.read(b))!=-1) {
fos.write(b,0,len);
}

fos.flush();
fos.close();
is.close();
rs.close();
ps.close();
}

public Connection getConn() {
Connection conn = null;
String url = "jdbc:mysql://localhost/dandan?user=root&password=dada&characterEncoding=utf-8";
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}

相關文章