无法在sqlexception中处理MysqlIntegrity异常

时间:2014-07-17 06:47:50

标签: java jdbc

我试图捕获SQL异常的catch子句中的MysqlIntegrityException但它似乎没有在SQL异常的catch块中处理它。可能是什么原因以及如何解决它。

catch(SQLException e)
{
//not reaching here
}

1 个答案:

答案 0 :(得分:0)

抱歉,无法重现此内容。

这是我在MySQL监视器中创建的一些表:

mysql> create table a (id int not null primary key auto_increment);
Query OK, 0 rows affected (0.09 sec)

mysql> create table b (b_id int not null primary key auto_increment, a_id int not null);
Query OK, 0 rows affected (0.06 sec)

mysql> alter table b add constraint a_fk foreign key (a_id) references a(id);
Query OK, 0 rows affected (0.19 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> insert into a() values();
Query OK, 1 row affected (0.04 sec)

mysql> insert into a() values();
Query OK, 1 row affected (0.03 sec)

mysql> insert into b (a_id) values (1);
Query OK, 1 row affected (0.04 sec)

让我们测试外键约束是否有效:

mysql> delete from a where id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`b`, CONSTRAINT `a_fk` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`))

然后我编写了这个Java类:

import java.sql.*;

public class MySQLExceptionTest {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "user", "password");
        PreparedStatement stmt = c.prepareStatement("DELETE FROM a WHERE id = 1");
        try {
            stmt.execute();
        }
        catch (SQLException e) {
            System.out.println("Got a " + e.getClass().getName() + " with message " + e.getMessage());
        }
    }
}

当我运行这个课程时,我得到了以下输出:

Got a com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException with message Cannot delete or update a parent row: a foreign key constraint fails (`test`.`b`, CONSTRAINT `a_fk` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`))

我的代码可以捕获此异常,为什么不能使用?好吧,几乎完全没有你的任何代码,我只能提供几个推测性答案:

  • 异常被捕获到try块内的某个地方,可能已被包裹并重新抛出,
  • try块中的代码启动一个新的Thread,并在新线程中引发异常。