0

我想通过 java,文件选择器将图像文件保存到数据库。

我的数据库名称是“gallery_images”,表名是“image_table”,列是“image id(int)”autoincrement、“image(longblob)”和“username(varchar2(45))”。

我可以通过工作台将图像添加到我的mysql数据库到longblob(右键单击longblob单元格,“从文件中加载值”),当我执行它时,它给了我这个代码:

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

这 ”?” 应该是图像,所以我没有通过这段代码学到太多东西。当我通过 java 读取文件时,如何将它插入到我的表中(使用 jdbc)?

完成此操作后,我想查询该表中的每个数据:

SELECT * FROM image_table;

我想将图像从数据库保存到列表:

private List<Image> images;

我想,我应该使用“while(resultset.next()”,但是我应该如何从结果集中获取图像呢?有人可以帮我吗?谢谢!

4

4 回答 4

1

使用 JDBC 将图像(从本地磁盘上的 JPG 文件)插入 MySQL db:

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(); }  


    }

}
于 2013-03-05T21:30:32.870 回答
1

使用 JDBC 从 MySQL db 读取图像,适用于 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;

    }


}
于 2013-03-05T21:34:13.613 回答
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();
    }
  }
}
于 2013-03-05T22:11:39.683 回答
0

如果您只想添加一张图片,我想您可以使用:

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

于 2013-03-07T01:35:14.190 回答