gpt4 book ai didi

mysql - 如何在 Java 应用程序中使用 Hibernate 和 MySQL 清除或删除数据库

转载 作者:行者123 更新时间:2023-11-29 20:27:31 24 4
gpt4 key购买 nike

是否存在删除单个数据库中所有表的mysql查询(使用MariaDB 10.x.x)或Hibernate HQL?现在我正在尝试使用下面的代码,但它不会对数据库执行任何操作。由于我使用的是 Hibernate 5.x.x,因此 createSQLQuery 已被弃用;因此我使用 createNativeQuery 代替

tx = s.beginTransaction();
Session s = getSessionFactory().openSession();
Transaction tx = null;

try {
tx = s.beginTransaction();
s.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0");
s.createNativeQuery("DROP DATABASE restaurantapp");
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
s.close();
}

最佳答案

解决方案

SQL 命令很好,但我不知道需要在每个 native 查询后添加 .executeUpdate();

解决方案代码:

Session s = getSessionFactory().openSession();
Transaction tx = null;

try {
tx = s.beginTransaction();
s.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate();
s.createNativeQuery("DROP DATABASE restaurantapp").executeUpdate();
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
s.close();
}

关于mysql - 如何在 Java 应用程序中使用 Hibernate 和 MySQL 清除或删除数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39217606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com