?? imagelibraryservice.java
字號:
package com.allanlxf.jdbc.core20;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.allanlxf.jdbc.util.ConnectionFactory;
import com.allanlxf.jdbc.util.JdbcUtil;
/**
* Add your description here.
*
* @author alan
* @version 1.0
*/
public class ImageLibraryService
{
public void addImage(long id, String imageName, String path) throws SQLException
{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
String sql = "insert into ImageLibrary(id, name, image)";
sql += " VALUES(?, ?, empty_blob())";
ps = con.prepareStatement(sql);
ps.setLong(1, id);
ps.setString(2, imageName);
ps.executeUpdate();
ps.close();
ps = con.prepareStatement("select image from ImageLibrary WHERE id = ? for update ");
ps.setLong(1, id);
rs = ps.executeQuery();
if (rs.next())
{
Blob image = rs.getBlob(1);
OutputStream out = image.setBinaryStream(0);
BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
BufferedInputStream bufferedIn = new BufferedInputStream(new FileInputStream(path));
int c;
while ((c = bufferedIn.read()) != -1)
{
bufferedOut.write(c);
}
bufferedIn.close();
bufferedOut.close();
}
con.commit();
} catch (Exception e)
{
e.printStackTrace();
try
{
con.rollback();
} catch (SQLException se)
{
}
throw new SQLException(e.getMessage());
} finally
{
JdbcUtil.close(rs, ps, con);
}
}
public void restoreImage(long id, String filename) throws SQLException
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
try
{
con = ConnectionFactory.getConnection();
String sql = "SELECT image From ImageLibrary Where id = " + id;
st = con.createStatement();
rs = st.executeQuery(sql);
while (rs.next())
{
Blob image = rs.getBlob("image");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
BufferedInputStream in = new BufferedInputStream(image.getBinaryStream());
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
in.close();
out.close();
}
} catch (Exception e)
{
throw new SQLException(e.getMessage());
} finally
{
JdbcUtil.close(rs, st, con);
}
}
public static void main(String[] args) throws Exception
{
ImageLibraryService service = new ImageLibraryService();
if (args.length == 3)
{
service.addImage(Long.parseLong(args[0]), args[1], args[2]);
} else
{
service.restoreImage(Long.parseLong(args[0]), args[1]);
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -