Blob----(Binary Long Object)就是二进制长对象的意思,Blob通常用于存储大文件,比如说:一张图片或一个声音文件
使用Blob列可以把图片、声音等文件的二进制数据保存在数据库,并可以从数据库里恢复成指定文件。
所以使用Blob数据插入数据库需要使用PreparedStatement,该对象的方法:
-----setBinaryStream(int parameterIndex,InputSteam x),可以为指定参数传入二进制输入流,从而可以实现将
Blob数据保存到数据库的功能。
当我们需要从ResultSet里取出Blob数据时,可以调用ResultSet的getBlob(int columnIndex)方法,
该方法将返回一个Blob对象,Blob对象提供了getBinaryStream方法来获取该Blob数据的输入流,也
resultset 遍历可使用Blob对象提供了getByte方法直接取出该Blob对象封装的二进制数据。
为了把图片放入数据库,本程序先使用如下SQL语句来建立一个数据表:
--------------------------------------------------------------
create table img_table
(
img_id int auto_increment primary key,
img_name varchar(255),
---创建一个mediumblob类型的数据列,用于保存图片数据
img_data mediumblob
);
注意:MySQL数据库里的BLOB类型最多只能存储64k内容,这可能不够满足实际用途。所以使用mediumblob类型,
该类型的数据列可以存储16M内容。
-----------------------下面的程序可以执行图片"上传"-----实际上就是将图片保存到数据库,并在右边的
列表框显示图片的名字,当用户双击列表框的图片名时,左边窗口将显示该图片
------实质就是根据选中的ID从数据库里查图片,并将其显示出来。
------程序清单:
public class BlobTest
{
JFrame jf=new JFrame("图片管理");
private static Connection conn;
private static PreparedStatement insert;
private static PreparedStatement query;
private static PreparedStatement queryAll;
//定义一个DefaultListModel对象
private DefaultListModel imageModel=new DefaultListModel();
private JList imageList=new JList(imageModel);
private JTextField filePath=new JTextField(26);
private JButton browserBn=new JButton("...");
private JButton uploadBn=new JButton("上传");
private JLabel imageLabel=new JLabel();
//以当前路径创建文件选择器
JFileChooser chooser=new JFileChooser(".");
//创建文件过滤器
ExtensionFileFilter filter=new ExtensionFileFilter();
static
{
try
{
Properties props=new Properties();
props.load(new FileInputStream("mysql.ini"));
String Property("driver");
String Property("url");
String Property("user");
String Property("pass");
Class.forName(driver);
//获取数据库连接
Connection(url,user,pass);
/
/创建执行插入的PreparedStatement对象,该对象执行插入后可以返回自动生成的主键
insert=conn.prepareStatement("insert into img_table values(null,?,?) ",
Statement.RETURN_GENERATED_KEYS);
//创建两个PreparedSatement对象,用于查询指定图片,查询所有图片
query=conn.preparedStatement(
" select img_data from img_table where img_id=? "
);
queryAll=conn.preparedStatement(
" select img_id,img_name from img_table "
);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void init()throws SQLException
{
//------初始化文件选择器------
filter.addExtension("jpg");
filter.addExtension("jpeg");
filter.addExtension("gif");
filter.addExtension("png");
filter.setDescription("图片文件(*.jpg,*.jpeg,*gif,*.png)");
chooser.addChoosableFileFilter(filter);
//禁止"文件类型"下拉列表中显示"所有文件"选项
chooser.setAcceptAllFileFilterUsed(false);
//------初始化程序界面--------
fillListModel();
filePath.setEditable(false);
//只能单选
imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel jp=new JPanel();
jp.add(filePath);
jp.add(browserBn);
browserBn.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//显示文件对话框
int result=chooser.showDialog(jf,"浏览图片文件上传");
//如果用户选择了APPROVE(赞同)按钮,即打开,保存及其等效按钮
if(result==JFileChooser.APPROVE_OPTION)
{
filePath.SelectedFile().getPath());
}
}
}
);
jp.add(uploadBn);
uploadBn.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent avt)
{
//如果上传文件的文本框有内容
Text().trim().length>0)
{
//将指定文件保存到数据库
Text());
//清空文本框内容
filePath.setText("");
}
}
}
)
;
JPanel left=new JPanel();
left.setLayout(new BorderLayout());
left.add(new JScrollPane(imageLabel),BorderLayout.CENTER);
left.add(jp,BorderLayout.SOUTH);
jf.add(left);
imageList.setFixedCellWidth(160);
jf.add(new JScrollPane(imageList),BorderLayout.EAST);
imageList.addMouseListener(
new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
//如果鼠标双击
ClickCount()>=2)
{
//
取出选中的List项
ImageHolder cur=(SelectedValue();
try
{
//显示选中项对应的Image
Id());
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
}
}
}
);
jf.setSize(620,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
//--------------查img_table填充ListModel---------------
public void fillListModel()throws SQLException
{
ResultSet rs=null;
try
{
//先清除所有元素
imageModel.clear();
/
/执行查询
uteQuery();
//把查询的全部记录添加到ListModel中
())
{
imageModel.addElement(new Int(1),rs.getString(2)));
}
}
finally
{
if(rs!=null)
{
rs.close();
}
}
}
//---------将指定图片放入数据库-------------
public void upload(String fileName)
{
InputStream is=null;
try
{
/
/截取文件名
String imageName=fileName.substring(
fileName.lastIndexOf('\\')+1,fileName.lastIndexOf('.')
);
//设置图片名参数
insert.setString(1,imageName);
File f=new File(fileName);
is=new FileInputStream(f);
//设置二进制流参数
insert.setBinaryStream(2,is,(int)f.length());
int uteUpdate();
if(affect==1)
{
//重新更新ListModel,将会让JList显示最新的图片列表
fillListModel();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(is!=null)
{is.close();}
}
catch(Exception e)
{}
}
}
//------根据图片ID来显示图片----------
public void showImage(int id)throws SQLException
{
ResultSet rs=null;
try
{
//设置参数
query.setInt(1,id);
//执行查询
uteQuery();
())
{
/
/取出Blob列
Blob Blob(1);
//取出Blob列里的数据
ImageIcon icon=new Bytes(1L,(int)imgBlob.length()));
imageLabel.setIcon(icon);
}
}
finally
{
if(rs!=null)
{
rs.close();
}
}
}
public static void main(String[] args)throws SQLException
{
new BlobTest().init();
}
}
//创建FileFilter的子类,用以实现文件过滤功能
class ExtensionFilter extends FilteFilter
{
private String description="";
private ArrayList<String> extensions=new ArrayList<String>();
//自定义方法,用于添加文件扩展名
public void addExtension(St
ring extension)
{
if(!extension.startsWith("."))
{
extension="."+extension;
extensions.LowerCase());
}
}
//用于设置改文件过滤器的描述文本
public void setDescription(String aDescription)
{
description=aDescription;
}
//继承FileFilter类必须实现的抽象方法,返回该文件过滤器的描述文本
public String getDescription()
{
return description;
}
//继承FileFilter类必须实现的抽象方法,判断该文件过滤器是否接受该文件
public boolean accept(File f)
{
//如果该文件是路径,接受该文件
if(f.isDirectory()){ return true;}
//将文件名转为小写(全部转为小写后比较,用于疏忽文件名大小写)
String Name().toLowerCase();
//遍历所有可接受的扩展名,如果扩展名相同,该文件就可以接受。
for(String extension:extensions)
{
dsWith(extension))
{
return true;
}
}
return false;
}
}
//创建一个ImageHolder类,用于封装图片名、图片ID
class ImageHolder
{
/
/封装图片的ID
private int id;
//封装图片的图片名字。
private String name;
public ImageHolder()
{}
public ImageHolder(int id,String name)
{
this.id=id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return this.id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论