下面是一个Java连Oracle数据库的一个简单测试,以及在Oracle中存储图片信息
import java.awt.Container;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
class ReadPic extends JFrame{
public ReadPic(){
try{
/*
* 建立数据库的连接
*/
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:zgydb","jenny","888888");
Statement stmt = conn.createStatement();
/*
*执行数据查询语句
*/
ResultSet rs = stmt.executeQuery("select * from images");
rs.next();
/*
* 获取读取到的信息
*/
//String name = rs.getString(1);
int length = rs.getInt(2);
InputStream is = rs.getBinaryStream(3); //准备字节流
byte[] b = new byte[length];
is.read(b); //读取字节信息
/*
* 显示图片
*/
ImageIcon icon = new ImageIcon(b);
Container cont = this.getContentPane();
JLabel label = new JLabel(icon);
cont.add(label);
this.setSize(300,200);
this.setLocation(300,300);
this.validate();
}catch(Exception e){
System.out.println("wrong!");
}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String args[]){
new ReadPic();
save pic
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class SavePic extends JFrame implements ActionListener{
JTextField tf = new JTextField();
public SavePic(){
JButton jb = new JButton("单击选择待存储文件");
jb.addActionListener(this);
this.getContentPane().add(tf,"North");
this.getContentPane().add(jb,"South");
this.setSize(300,150);
this.setLocation(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
FileDialog jf = new FileDialog(this); //构造选择文件对话框
jf.setVisible(true);
String fname = jf.getFile();
String path = jf.getDirectory() + fname; //获取用户所选择文件的路径
File f = new File(path);
long length = f.length();
try{
FileInputStream fis = new FileInputStream(f); //准备文件输入流
/*
* 建立与Oracle数据库之间的连接
*/
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:zgydb","jenny","888888");
PreparedStatement pstmt = conn.prepareStatement("insert into images values(?,?,?)");
//给参数赋值
pstmt.setString(1,fname);
pstmt.setInt(2,(int)length);
pstmt.setBinaryStream(3,fis,(int)length);
//执行插入数据库的语句
pstmt.executeUpdate();
pstmt.close();
tf.setText("图片已经成功存储到数据库中!"); //显示存储成功提示信息
}catch(Exception e){
tf.setText("图片存储不成功!"); //显示存储失败提示信息
}
}
public static void main(String[] args) {
new SavePic();
}
}
}
}
阅读(2708) | 评论(0) | 转发(0) |