2013-03-05 48 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'));

相关问题