【问题标题】:How to browse and save image into Oracle DB using SQL?如何使用 SQL 浏览图像并将其保存到 Oracle DB 中?
【发布时间】:2014-04-25 04:18:51
【问题描述】:

我正在使用 Java/Swing/Oracle 10g 数据库和
有一个名为 photo 的表,photoID 作为数字,photo 作为 blob,我正在使用 JFileChooser 打开并显示一张照片,但它不会将其保存到我的数据库中。

错误

java.sql.SQLException: Invalid column index

代码

enter code here

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Photo.java
 *
 * Created on Mar 18, 2014, 5:51:22 PM
 */

package ems;

import java.io.*;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import java.sql.*;

/**
 *
 * @author css102134
 */
public class Photo extends javax.swing.JFrame {

    /** Creates new form Photo */

    public Photo() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        Jlabel = new javax.swing.JLabel();
        browseButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Jlabel.setText("choose file:");

        browseButton.setText("browse");
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("photo");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(Jlabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(browseButton)
                .addContainerGap(241, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Jlabel)
                    .addComponent(browseButton))
                .addGap(29, 29, 29)
                .addComponent(jLabel2)
                .addContainerGap(206, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {

        JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
File f = fc.getSelectedFile();
String path = f.getAbsolutePath();
Jlabel.setIcon(new ImageIcon(path));
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");
 String url="jdbc:oracle:thin:@localhost:1521:XE";
            String u="ems2";
            String p="ems2";
Connection con = DriverManager.getConnection(url,u,p);

PreparedStatement ps = con.prepareStatement("insert into photo (photos) values(?)");

  FileInputStream fin=new FileInputStream("D:/Workspace/ems_ui/photos/prasanth.jpg");
  System.out.println("hi");
  ps.setBinaryStream(3, fin);
int status = ps.executeUpdate();
if(status>0)
{
jLabel2.setText("successfully inserted in Db");
}
else
{
jLabel2.setText("Image not inserted in Db");
}
con.close();

}
catch(Exception e)
{
System.out.println(e);
}

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Photo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel Jlabel;
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration

}

【问题讨论】:

  • 我看不到 saveButtonActionPerformed(evt);您的帖子中的函数实现离子,但您正在调用该方法..该方法代码在哪里??
  • java.sql.SQLException: Invalid column index is the error am getting
  • 嗨@Stunner,我想保留保存按钮,但我认为在浏览器中实现了保存操作

标签: java sql oracle jdbc runtime-error


【解决方案1】:

有一些东西会跳出来......

您创建了一个PreparedStatementPreparedStatement ps = con.prepareStatement("insert into photo values(?,?)");,但只绑定了一个值ps.setBinaryStream(3, fin, len);,甚至没有绑定到有效参数...

photoID 参数需要从查询中排除,或者值需要绑定到参数。

假设 ID 是由数据库自动生成的,那么您可以使用...

PreparedStatement ps = con.prepareStatement("insert into photo (photo) values(?)");
ps.setBinaryStream(1, fin);

如果没有,您将需要使用更像...的东西

PreparedStatement ps = con.prepareStatement("insert into photo (photoID, photo) values(?, ?)");
ps.setInt(1, id);
ps.setBinaryStream(2, fin);

此外,您永远不会关闭流,这会使资源保持打开状态并阻止它们被标记为垃圾回收。黄金法则,如果你打开,你就关闭它......

如果您使用的是 Java 7...

try (FileInputStream fin = new FileInputStream(f); Connection con = DriverManager.getConnection(url, u, p)) {...

否则……

FileInputStream fin = null;
Connection con = null;
try {
    fin = new FileInputStream(f);
    con = DriverManager.getConnection(url, u, p);
    //...
} catch (...) {
    //..
} finally {
    try {
        fin.close();
    } catch (Excepiton exp) {
    }
    try {
        con.close();
    } catch (Excepiton exp) {
    }
}

【讨论】:

  • 嗨@madProgrammer,现在我正确关闭了连接,并且我已经使photoid自动生成并使用序列和触发器从3开始,当我使用ps.setBinaryStream(1,fin)时;此语句并添加它在线程“AWT-EventQueue-0”中显示异常 java.lang.AbstractMethodError: oracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;
  • 您是否尝试过ps.setBinaryStream(int, InputStream, long); 喜欢您的原始代码?在关闭 Connection 之前,您可能还需要打开自动提交或提交更改
  • 您可能还想阅读this
  • 嗨@madProgammer,这是我在遵循您的想法后更新的代码
  • @prasanth 你可能还想通读this
猜你喜欢
  • 1970-01-01
  • 2014-09-16
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
相关资源
最近更新 更多