java - 我从 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
阻塞,但我不知道为什么。
解决方案
首先,回答你的问题,你的问题是那"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用于此示例的日志记录目的。
推荐阅读
- unit-testing - phpunit 回复无法识别的选项 --env
- r - 关于在 HPC 集群上运行 Rmpi 和 foreach 的几个问题
- .htaccess - 去掉url的post号
- django - Django REST Framework 中不同 API 方法的基于角色的访问控制
- java - 从矩阵绘制和显示位图
- laravel - 我应该把 Homestead 文件夹放在哪里?
- gradle - 为什么 Apache Beam 源代码构建失败?
- angular - 如何以角度访问函数外部的变量
- r - 我想计算出数据点(纬度/经度)与 R 中形状文件边缘的距离,然后将标准应用于数据点?
- c# - TwinCAT 3.0 自动化接口:获取本地 netId 进行广播搜索