多謝大家,我已經弄好了,就是用的樓上那為仁兄的方法!太感謝了 !
表是:
id int
imageS image
[code]
public void save_actionPerformed(ActionEvent e) {??//保存到數據庫中
? ? try{
? ?? ?File tmpFile = new File(path);
? ?? ?FileInputStream in = new FileInputStream(tmpFile);
? ?? ?BufferedInputStream inFile = new BufferedInputStream(in);
? ?? ?//獲取圖片大小
? ?? ?int a = Integer.parseInt(String.valueOf(tmpFile.length()));
? ?? ?System.out.println(a / 1000 + "KB");
? ?? ?byte len[] = new byte[a];
? ?? ?//讀字節
? ?? ?while (inFile.read(len) != -1) {
? ?? ?}
? ?? ?int pos=1;
? ?? ?//設置id號碼
? ?? ?String sql = "select count(*) as total from product";
? ?? ?pst = con.prepareStatement(sql);
? ?? ?rs = pst.executeQuery();
? ?? ?if (rs.next()) {
? ?? ?? ?pos=rs.getInt(1);
? ?? ?? ?pos++;
? ?? ?}
? ?? ?//插入記錄
? ?? ?sql = "insert into product values(?,?)";
? ?? ?pst = con.prepareStatement(sql);
? ?? ?pst.setInt(1, pos);
? ?? ?pst.setBytes(2, len);
? ?? ?pst.executeUpdate();
? ?? ?JOptionPane.showMessageDialog(this, "插入記錄完畢!", "消息",
? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ? JOptionPane.INFORMATION_MESSAGE);
? ? }
? ? catch(IOException ex){
? ?? ?System.out.println("I/O錯誤!"+ex.getMessage());
? ?? ?ex.printStackTrace();
? ? }
? ? catch(Exception ex){
? ?? ?System.out.println("插入記錄錯誤!"+ex.getMessage());
? ?? ?ex.printStackTrace();
? ? }
??}
[/code]
我使用了一個下拉彩旦
[code]
??public void item_itemStateChanged(ItemEvent e) {??//提取圖片
? ? if(item.getSelectedItem().toString().equals("------ID------")){
? ? }
? ? else{
? ?? ?int tmpId = Integer.parseInt(item.getSelectedItem().toString());
? ?? ?try {
? ?? ???String sql = "select * from product where id=?";
? ?? ???pst = con.prepareStatement(sql);
? ?? ???pst.setInt(1, tmpId);
? ?? ???rs = pst.executeQuery();
? ?? ???if (rs.next()) {
? ?? ?? ? int id = rs.getInt("id");
? ?? ?? ? //提取圖片字節
? ?? ?? ? byte src[] = rs.getBytes("imageS");
? ?? ?? ? //還原
? ?? ?? ? ImageIcon i = new ImageIcon(src);
? ?? ?? ? ima.setIcon(i);
? ?? ???}
? ?? ?}
? ?? ?catch (SQLException ex) {
? ?? ???System.out.println("從數據庫讀取圖片錯誤!");
? ?? ???System.out.println(ex.getMessage());
? ?? ?}
? ? }
??}
[/code]