首页 > 解决方案 > 我从 MySQL 获取数据以显示在 jTable 中,但出现异常

问题描述

这是代码:

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

标签: javajdbcmysql-connector

解决方案


首先,回答你的问题,你的问题是那"select *from patient where PatientID='" + PatientID + "'"不是一个有效的SQL陈述,因为*FROM从句在一起。相反,在其上添加一个空格。

只是改变:

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

和:

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

并且,作为旁注,只是一个建议:如果您的 SQL 有参数,请不要使用Statement接口,而是使用PreparedStatement接口。否则,您的代码将容易受到SQL 注入的攻击。

并且,请将您的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用于此示例的日志记录目的。


推荐阅读