有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用java在postgres数据库中上传和显示图像

在eclipse中使用java从postgres数据库插入和检索图像的程序

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WriteImage {

public static void main(String[] args) {

    Connection con = null;
    PreparedStatement pst = null;
    FileInputStream fin = null;

    String url = "jdbc:postgresql://localhost/testdb";
    String user = "user12";
    String password = "34klq*";               

    try {

        File img = new File("woman.jpg");
        fin = new FileInputStream(img);

        con = DriverManager.getConnection(url, user, password);

        pst = con.prepareStatement("INSERT INTO images(data) VALUES(?)");
        pst.setBinaryStream(1, fin, (int) img.length());
        pst.executeUpdate();

    } catch (FileNotFoundException | SQLException ex) {
        Logger lgr = Logger.getLogger(WriteImage.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {

        try {
            if (pst != null) {
                pst.close();
            }
            if (con != null) {
                con.close();
            }
            if (fin != null) {
                fin.close();
            }

        } catch (IOException | SQLException ex) {
            Logger lgr = Logger.getLogger(WriteImage.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);

        }
    }
}

}


共 (0) 个答案