1. 程式人生 > 其它 >jdbc 如何讀寫 blob 型別的資料?

jdbc 如何讀寫 blob 型別的資料?

向資料表中插入大資料型別

獲取連線
Connectionconn=JDBCUtils.getConnection();
		
Stringsql="insertintocustomers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatementps=conn.prepareStatement(sql);
//java專案wwwfhadminorg
//填充佔位符
ps.setString(1,"張強");
ps.setString(2,"[email protected]");
ps.setDate(3,newDate(newjava.util.Date().getTime()));
//操作Blob型別的變數
FileInputStreamfis=newFileInputStream("xhq.png");
ps.setBlob(4,fis);
//執行
ps.execute();
		
fis.close();
JDBCUtils.closeResource(conn,ps);

3 修改資料表中的Blob型別欄位

Connectionconn=JDBCUtils.getConnection();
Stringsql="updatecustomerssetphoto=?whereid=?";
PreparedStatementps=conn.prepareStatement(sql);
//java專案wwwfhadminorg
//填充佔位符
//操作Blob型別的遊戲代理變數
FileInputStreamfis=newFileInputStream("coffee.png");
ps.setBlob(1,fis);
ps.setInt(2,25);
ps.execute();
fis.close();
JDBCUtils.closeResource(conn,ps);

4 從資料表中讀取大資料型別

//java專案wwwfhadminorg
Stringsql="SELECTid,name,email,birth,photoFROMcustomerWHEREid=?";
conn=getConnection();
ps=conn.prepareStatement(sql);
ps.setInt(1,8);
rs=ps.executeQuery();
if(rs.next()){
	Integerid=rs.getInt(1);
Stringname=rs.getString(2);
	Stringemail=rs.getString(3);
Datebirth=rs.getDate(4);
	Customercust=newCustomer(id,name,email,birth);
System.out.println(cust);
//讀取Blob型別的欄位
	Blobphoto=rs.getBlob(5);
	InputStreamis=phohttp://www.walajiao.comto.getBinaryStream();
	OutputStreamos=newFileOutputStream("c.jpg");
	byte[]buffer=newbyte[1024];
	intlen=0;
	while((len=is.read(buffer))!=-1){
		os.write(buffer,0,len);
	}
JDBCUtils.closeResource(conn,ps,rs);
		
	if(is!=null){
		is.close();
	}
		
	if(os!=null){
		os.close();
	}