使用NetBeans+Java从Access取数到JTable时遇Ucanaccess SQL异常
搞定Ucanaccess的SQL语法错误问题
嘿,这个unexpected token: DOCTOR错误我太熟了——完全是你的SQL语句语法出问题了!我帮你一步步拆解并修复:
1. 先揪出SQL里的致命问题
你拼接后的SQL语句其实是这样的:
Select p.Name AS Patient, p.Disesae AS Disease, Doctor.Name AS Doctor Doctor.Visiting_Day AS SechduleDay from Patients AS p where p.Disease = Doctor.Specialization
这里有三个核心问题:
- 缺少逗号:
Doctor.Name AS Doctor和后面的Doctor.Visiting_Day之间没有加逗号,数据库解析时直接把Doctor当成了非法关键字,这就是报错的直接原因 - 拼写错误:
Disesae应该是Disease,SechduleDay应该是ScheduleDay——这种小错误很容易忽略,但会导致字段找不到 - 表连接逻辑错误:直接用
where关联Patients和Doctor会产生笛卡尔积(两张表的所有数据无意义组合),正确的做法是用JOIN显式指定关联条件
2. 修正后的正确SQL
把SQL改成带显式JOIN的版本,同时修正所有拼写问题:
String sql1 = "SELECT p.Name AS Patient, p.Disease AS Disease, d.Name AS Doctor, d.Visiting_Day AS ScheduleDay " + "FROM Patients AS p " + "JOIN Doctor AS d ON p.Disease = d.Specialization";
这里我给Doctor表加了别名d,和Patients的p保持一致,代码读起来更清爽;用JOIN ... ON替代原来的where条件,逻辑更严谨,不会出现意外的数据组合。
3. 完整的修正代码
另外,我还给你加上了资源关闭的逻辑(避免数据库连接泄漏),替换你的viewAppointment方法就行:
public void viewAppointment() throws ClassNotFoundException, SQLException { Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // 把资源变量声明在try外面,方便finally里统一关闭 Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/AQ/Documents/NetBeansProjects/MC170402106_2/MC170402106.accdb"); String sql1 = "SELECT p.Name AS Patient, p.Disease AS Disease, d.Name AS Doctor, d.Visiting_Day AS ScheduleDay " + "FROM Patients AS p " + "JOIN Doctor AS d ON p.Disease = d.Specialization"; ps = conn.prepareStatement(sql1); rs = ps.executeQuery(); jTable1.setModel(DbUtils.resultSetToTableModel(rs)); } catch (Exception e) { // 显示具体错误信息比直接抛异常更方便调试 JOptionPane.showMessageDialog(null, "出错啦:" + e.getMessage()); e.printStackTrace(); // 控制台打印堆栈信息,方便排查深层问题 } finally { // 一定要关闭资源,不然数据库连接会被占着 if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); } }
4. 最后几个小提醒
- 确认你的数据库表名是
Patients和Doctor(Access不区分大小写,但尽量和代码里一致) - 检查字段名:
Patients的疾病字段确实是Disease,Doctor的专长字段是Specialization,出诊日是Visiting_Day,别搞混了 - 以后调试SQL的时候,可以把拼接后的语句复制到Access里直接运行,能快速定位语法问题
内容的提问来源于stack exchange,提问作者Abdul Qayyum
相关产品推荐
相关产品推荐

