2013-03-05 47 views
0

我想通過java,文件選擇器將圖像文件保存到數據庫。我的db名稱是「gallery_images」,表名是「image_table」,列是「圖像id(int)」自動增量,「圖像(longblob)」和「用戶名(varchar2(45))」。如何使用sql代碼將圖像文件保存到mysql以及如何使用java顯示它們?

我可以通過工作臺到LONGBLOB圖像添加到我的MySQL數據庫(右鍵單擊LONGBLOB細胞,「負載值從文件」),並在㈡執行它,它給了我這樣的代碼:

INSERT INTO `image_table`.`gallery_images` (`image`, `username`) VALUES (?, 'viktor'); 

「?」應該是圖像,所以我沒有學到太多的代碼。當我通過java讀取文件時,如何將它插入到我的表中(使用jdbc)?

當我完成這件事,我想每一個數據從表中查詢:

SELECT * FROM image_table; 

我想從DB中的圖像保存到列表:

private List<Image> images; 

我想,我應該使用「while(resultset.next()」),但我應該如何從結果集中獲得圖像? 可以幫助我嗎?謝謝!

+3

(爲什麼)您是否需要將圖像保存到數據庫中? http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Andreas 2013-03-05 19:55:02

+0

我想創建一個JAR程序給我的朋友,他應該從DB讀取和插入數據,比如like image – victorio 2013-03-05 19:56:08

+2

請參閱[「從Java到Android序列化圖像(與Swing兼容)的最佳方式是什麼?'](http://stackoverflow.com/a/10004271/597657)。 – 2013-03-05 19:57:02

回答

1

圖像插入在本地磁盤PG文件)到MySQL數據庫使用JDBC:

從MySQL
package dbTest; 

import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStream; 
import java.sql.DriverManager; 

import com.example.pompeymenu.Dish; 
import com.mysql.jdbc.Connection; 
import com.mysql.jdbc.PreparedStatement; 

public class DishAdder { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int bytesRead; 

     try { 
       //setting filenames 
       File[] filesd = new File[6]; 
       String fileName[] = new String[] {"1.JPG", "2.JPG", "3.JPG", "4.JPG", "5.JPG", "6.JPG"}; 
       String dishName[] = new String[] { 
         "Cake with cherries", 
         "Tiramisu", 
         "Cheese cake", 
         "Pana Cotta", 
         "Ice cream", 
         "Apple Pie" 
       }; 

       Connection conn = null; 
       String userName = "your_user_name"; 
       String password = "your_db_password"; 
       String url = "jdbc:mysql://your_db_url"; 
       Class.forName("com.mysql.jdbc.Driver").newInstance(); 
       conn = (Connection) DriverManager.getConnection(url, userName, password); 
       //Statement s = null; 
       PreparedStatement s = null; 
       String qryInsert = "INSERT INTO MENU (DISH_NAME, DISH_IMG) VALUES (?, ?)";     

       //for (int i=5; i<6; i++) { 
        int i=5; 
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        filesd[i] = new File("E:/Android/Images/" + fileName[i]); 
        InputStream is = new FileInputStream(filesd[i]); 
        byte[] b = new byte[8096]; 
        while ((bytesRead = is.read(b)) != -1) { 
          bos.write(b); 
        } 
        byte[] bytes = bos.toByteArray(); 

        //save byte[] to DB 

         s = (PreparedStatement) conn.prepareStatement(qryInsert); 
         s.setString(1, dishName[i]); 
         s.setBytes(2, bytes); 
         s.executeUpdate(); 

       //} 

       s.close(); 
       conn.close(); 

     } catch (Exception e) { e.printStackTrace(); } 


    } 

} 
+0

http://benignosales.wordpress.com/2011/10/24/jsf-2-primefaces -pgalleria -exec -de-galeria-de-fotos/< - 這可能是一個解決方案,他做的差不多我想要的,通過primefaces將圖像文件上傳到mysql數據庫,然後瀏覽圖像來自數據庫,但它不顯示DAO文件,哪個(我認爲)真正的解決方案,如何將圖像上傳到數據庫,並將圖像下載到WebContent文件夾中的文件夾中 – victorio 2013-03-06 14:42:36

+0

http://knowledgeshare.awardspace.info /?p = 87 < - 這是另一個例子,但在這個項目中,程序不會將文件保存到文件夾中,而是轉到servlet doGet methot,並且該方法使魔法顯示圖像。我對嗎?我真的不明白,這是怎麼做的,但我會解釋它... – victorio 2013-03-06 15:10:49

1

讀取圖像數據庫使用JDBC,對我的作品在Android上:

import java.sql.DriverManager; 
import java.util.ArrayList; 

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 

import com.mysql.jdbc.Blob; 
import com.mysql.jdbc.Connection; 
import com.mysql.jdbc.ResultSet; 
import com.mysql.jdbc.Statement; 

/** 
* 
* Loads products from external MySql database, registered on db4free.net 
* 
* @author Rodion Altshuler 
* 
*/ 
public class CatalogDBSource implements CatalogSource{ 

    Connection conn=null; 
    String userName = "???"; 
    String password = "???"; 
    String url = "jdbc:mysql://???"; 

    /** 
    * Set this flag=true before calling getProducts(), for example, in order to make several requests to DB 
    * without re-opening connection each time 
    */ 
    public boolean flag_closeConnection=true; //if set to false, connection after getProducts() will retain opened 


    /**gets products from external DB 
    * needs INTERNET permission and MySQL driver  
    */ 
    @Override 
    public ArrayList<Product> getProducts() { 


     Thread getProductsThread = new Thread(new Runnable(){ 

      @Override 
      public void run(){ 

       try { 

        if (conn==null) { 
          Class.forName("com.mysql.jdbc.Driver").newInstance(); 
          conn = (Connection) DriverManager.getConnection(url, userName, password); 
        } 


        Statement s = (Statement) conn.createStatement(); 
        //String qry = "SELECT _ID, DISH_ID, DISH_NAME, DISH_CATEGORY, DISH_IMG FROM MENU";  
        String qry = "SELECT _ID, DISH_NAME, DISH_IMG FROM MENU";  
        s.executeQuery(qry); 

        ResultSet rs = null; 
        rs = (ResultSet) s.getResultSet(); 

        while (rs.next()) { 
         int id = rs.getInt("_ID"); 
         String productName = rs.getString("DISH_NAME"); 
         Blob b = (Blob) rs.getBlob("DISH_IMG"); 
         Bitmap productImg = bitmapFromBlob(b); 
         Product p = new Product(id, productName, productImg, ""); 
         //adding new item in ArrayList<Product> products, declared in interface CatalogSource 
         products.add(p); 
        } 


     rs.close();  
     s.close(); 


     if (flag_closeConnection) { 
      conn.close(); 
     } 


     } catch (Exception e) { 
      e.printStackTrace();      
     } 

     } 
    }); 

    getProductsThread.start(); 

    try { 
     getProductsThread.join(); 
    } catch (InterruptedException e1) { 
     e1.printStackTrace(); 
    } 

     return products; 
    } 

    /** 
    * Converts Blob to Bitmap 
    * @param b Blob object should be converted to Bitmap 
    * @return Bitmap object 
    */ 
    static Bitmap bitmapFromBlob(Blob b) { 


     Bitmap bitmap=null; 

     try { 
      byte[] temp = b.getBytes(1,(int) b.length()); 
      bitmap = BitmapFactory.decodeByteArray(temp,0, temp.length);    
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return bitmap; 

    } 


} 
1
package fileChooser; 

import java.io.*; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

import javax.swing.JFileChooser; 
import javax.swing.filechooser.FileFilter; 
import javax.swing.filechooser.FileNameExtensionFilter; 
public class FileChooserDialog { 
    public static void main(String[] args) throws IOException, SQLException { 
    JFileChooser fileopen = new JFileChooser(); 
    FileFilter filter = new FileNameExtensionFilter("c files", "c"); 
    fileopen.addChoosableFileFilter(filter); 

    int ret = fileopen.showDialog(null, "Open file"); 

    if (ret == JFileChooser.APPROVE_OPTION) { 
     File file = fileopen.getSelectedFile(); 
     System.out.println("file()===>>>"+file); 
     String url = "jdbc:mysql://localhost:3306/test"; 
     String username="root"; 
     String password="root"; 
     Connection con=null; 
     con = DriverManager.getConnection(url,username,password); 
     String sql = "INSERT INTO image (id, image) VALUES (?, ?)"; 
     PreparedStatement stmt = con.prepareStatement(sql); 
     stmt.setInt(1, 1); 
     //stmt.setString(2, "Java Official Logo"); 

     FileInputStream fis = new FileInputStream(file); 
     stmt.setBinaryStream(2, fis, (int) file.length()); 
     stmt.execute(); 
     fis.close(); 
     con.close(); 
    } 
    } 
} 
0

如果你想添加只有一個我想你可以使用:

INSERT INTO image_table(username,image)VALUES('viktor',load_file('path/image.jpg'));

相關問題