【问题标题】:I got data from MySQL to show up in the jTable but I'm getting an Exception我从 MySQL 获取数据以显示在 jTable 中,但出现异常
【发布时间】:2021-09-16 04:21:35
【问题描述】:

代码如下:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String PatientID = jtxtPatientID.getText();
        try {
            Connection con = ConnectionProvider.getCon();
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select *from patient where PatientID='" + PatientID + "'");
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            while(rs.first()){
                jlbPID.setVisible(false);
                jtxtPatientID.setEditable(false);
            }   
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Connection Error");
        }
    }  

我的代码将进入catch 块,但我不知道为什么。

【问题讨论】:

  • 您的代码格式不正确。
  • 谢谢你,伙计!
  • 如果您不介意,我会将我的 cmets 移至答案,如果您将其标记为已接受的答案,我们将不胜感激!

标签: java jdbc mysql-connector


【解决方案1】:

首先,回答你的问题,你的问题是"select *from patient where PatientID='" + PatientID + "'"不是一个有效的SQLstatement,因为*FROM子句是在一起的。而是在其上添加一个空格。

只是改变:

ResultSet rs = st.executeQuery("select *from patient where PatientID='" + PatientID + "'");

与:

ResultSet rs = st.executeQuery("select * from patient where PatientID='" + PatientID + "'");

并且,作为旁注,只是一个建议:Don't use the Statement interface if your SQL has parameters,而不是use the PreparedStatement interface。否则,您的代码将容易受到SQL Injection 的攻击。

并且,请将您的 catch 块更改为能够记录您的应用程序上发生的事情的 someting。调试时对你有很大帮助。我给你的建议基本上是这样的:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

    private static final Logger LOG = LogManager.getLogger(Myclass.class);

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String PatientID = jtxtPatientID.getText();
        String sql = "select * from patient where PatientID=?";
        try {
            Connection con = ConnectionProvider.getCon();
            PreparedStatement st = con.prepareStatement(sql);
            st.setString(1, PatientID);
            ResultSet rs = st.executeQuery();
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            while(rs.first()){
                jlbPID.setVisible(false);
                jtxtPatientID.setEditable(false);
            }   
        } catch (SQLException e) {
            LOG.error("Error while processing the SQL statement...", e);
            JOptionPane.showMessageDialog(null, "Connection Error");
        }
    }  

我使用log4j2 来记录这个例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多