我从 MySQL 中获取数据以显示在 jTable 中,但出现异常

I got data from MySQL to show up in the jTable but I'm getting an Exception

代码如下:

    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 块,但我不知道为什么。

首先,回答你的问题,你的问题是 "select *from patient where PatientID='" + PatientID + "'" 不是一个有效的 SQL 语句,因为 *FROM 子句在一起.相反,在其上添加一个 space。

只需更改:

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, instead, use the PreparedStatement interface. Otherwise, your code will be vulnerable to SQL Injection

并且,请将您的 catch 块更改为能够记录您的应用程序上发生的事情的东西。调试的时候会有很大的帮助。我向您推荐的基本上是这样的:

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 用于此示例的日志记录目的。