【问题标题】:try catch block not working with sql [closed]尝试 catch 块不适用于 sql [关闭]
【发布时间】:2018-06-13 20:04:22
【问题描述】:

我有以下java代码:

ResultSet rs2 = stmt.executeQuery("select * from teacher");  

        try
        {rs2.getInt("fee");
          System.out.println("found");
          stmt.executeUpdate("alter table teacher drop fee  ");
        }catch(SQLException e){
            System.out.println("not found");
            System.err.print(e);
            stmt.executeUpdate("alter table teacher add fee int ");
        } 

try 似乎从未被调用过。

【问题讨论】:

  • 您确定executeQuery 会毫无例外地返回吗?也许控制流甚至没有到达try
  • 请发布堆栈跟踪。
  • 如果您要检查数据库列是否存在,我建议使用DatabaseMetaData 而不是查询数据库表的内容
  • 不确定这是否是堆栈跟踪:java.sql.SQLException:结果集结束后com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:重复列名'fee'
  • 另外,stmt.executeUpdate 在更改表格时可能不是正确的调用;我会改用stmt.execute;更多的是通用用例

标签: java sql try-catch


【解决方案1】:

您需要执行rs2.next() 来获取第一行(以及后续行)。如:

ResultSet rs2 = stmt.executeQuery("select * from teacher");  

//rs2.next(); // reads one row!
  rs2.first();


try {
  rs2.getInt("fee");
  System.out.println("found");
  stmt.executeUpdate("alter table teacher drop fee  ");
} catch(SQLException e) {
  System.out.println("not found");
  System.err.print(e);
  stmt.executeUpdate("alter table teacher add fee int ");
} 

【讨论】:

  • 不起作用。行为没有改变
  • 堆栈跟踪是什么?
  • 请注意:rs2.first() 并非在所有 JDBC 驱动程序上都实现。但如果它有效,那就太好了。
猜你喜欢
  • 2012-03-26
  • 2020-01-27
  • 1970-01-01
  • 2012-10-02
  • 2022-06-10
  • 1970-01-01
  • 2013-01-01
  • 2018-02-14
  • 2010-12-25
相关资源
最近更新 更多