import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.sql.BLOB;
public class AddPicture {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
try
{
//need input the name of manager
//add the picture's path
String strName = "78976";
String strPhoto = "C:/001.jpg";
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String str="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
conn = DriverManager.getConnection(str,"scott","tigger");
BLOB blob = null;
conn.setAutoCommit(false);
File binaryFile = new File(strPhoto);
FileInputStream instream = new FileInputStream(binaryFile);
File file = new File(strPhoto);
InputStream fin = new FileInputStream(file);
PreparedStatement pstmt = conn.prepareStatement("UPDATE USER_INFO SET PHOTO = EMPTY_BLOB() WHERE USER_ID = ?");
pstmt.setString(1,strName);
pstmt.executeUpdate();
pstmt = conn.prepareStatement("SELECT * FROM USER_INFO WHERE USER_ID = ? FOR UPDATE");
pstmt.setString(1,strName);
ResultSet rset = pstmt.executeQuery();
if (rset.next())
{
blob = (BLOB) rset.getBlob("PHOTO");
}
pstmt = conn.prepareStatement("UPDATE USER_INFO SET PHOTO = ? WHERE USER_ID = ?");
OutputStream outstream = blob.setBinaryStream(1L);
int size = blob.getBufferSize();
byte[] buffer = new byte[size];
int length = -1;
while ((length = instream.read(buffer)) != -1)
outstream.write(buffer, 0, length);
instream.close();
outstream.close();
pstmt.setBlob(1,blob);
pstmt.setString(2,strName);
int i = pstmt.executeUpdate();
conn.commit();
pstmt.close();
fin.close();
conn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
if(conn != null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
java 写blob字段
最新推荐文章于 2023-07-25 17:31:42 发布