分类:
2008-01-14 23:43:33
package blobtest;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.Properties;
import java.io.*;
/**
*测试操作blob数据
*/
public class BlobTest
{
Connection con=null;
/**
* 往数据库中添加BLOB数据
*/
public void addBlob()
{
try
{
//创建一个PreparedStatement实例
PreparedStatement pstmt=con.prepareStatement("insert into blobtest values(1,?)");
File file = new File("c:\\golf.jpg") ;
FileInputStream fis = new FileInputStream(file);
//把输入流设置为预处理语句的对象。
pstmt.setBinaryStream(1, fis, (int)file.length());
//执行更新
pstmt.executeUpdate();
pstmt.close();
fis.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 创建一个表
*/
public void createTable()
{
try
{
con.createStatement().execute("create table blobtest (id int ,pic blob,"+
"constraint pk_blobtest primary key(id));");
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 从数据库中读取BLOB数据
*/
public void getBlob()
{
try
{
//创建一个Statement实例
Statement stmt=con.createStatement();
ResultSet rst=stmt.executeQuery("select * from blobtest where id=1");
rst.next();
//获得blob数据和它的输入流,然后通过输入流把数据写到文件中。
Blob blob = rst.getBlob("pic") ;
FileOutputStream out=new FileOutputStream(new File("c:/test.jpg"));
InputStream in=blob.getBinaryStream();
int i;
while((i=in.read())!=-1)
out.write(i);
//关闭输入、输出流.
in.close();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception
{
DataSource ds = null;
Context ctx = null;
Connection myConn = null;
try
{
ctx = getInitialContext();
ds = (javax.sql.DataSource) ctx.lookup("mysqlDS");
// ds=(javax.sql.DataSource)ctx.lookup("BOLb");
myConn = ds.getConnection();
BlobTest test = new BlobTest();
test.con = myConn;
System.out.println("Successed get connection!");
test.createTable();
System.out.println("Successed create table!");
test.addBlob();
System.out.println("add the blob type object!");
test.getBlob();
System.out.println("get the blob type object!");
myConn.close();
}
catch (Exception E)
{
myConn.close();
System.out.println("Init Error: " + E);
}
}
private static Context getInitialContext() throws Exception
{
String url = "t3://localhost:7001";
String user = "weblogic";
String password = "zhangjane";
Properties properties = null;
try
{
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
if (user != null)
{
properties.put(Context.SECURITY_PRINCIPAL, user);
properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);
}
return new InitialContext(properties);
}
catch(Exception e)
{
throw e;
}
}
}