gpt4 book ai didi

java - createTableIfNotExists 错误 - 关系已存在

转载 作者:行者123 更新时间:2023-11-29 13:58:40 25 4
gpt4 key购买 nike

在我的后端:

//create ConnectioSource
private static final String DB_NAME = "development";
private ConnectionSource connectionSource;
private String databaseUrl = "jdbc:postgresql://localhost:5432/" + DB_NAME;

public ConnectionSource getConnectionSource() {
try {
Class.forName("org.postgresql.Driver");
connectionSource = new JdbcConnectionSource(databaseUrl, "user", "333444");
return connectionSource;
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}

但是当我尝试重启后端时,我收到错误

"Caused by: org.postgresql.util.PSQLException: ERROR: relation "buyer_users" already exist"

ConnectionSource connectionSource = dbHelper.getConnectionSource();
TableUtils.createTableIfNotExists(connectionSource, BuyerUser.class);

当我使用 SQLite 数据库时,方法 createTableIfNotExists 工作正常,但是当我使用 postgres 时发生了什么?

更新:

我的解决方案:

 List<String> tablesList = new ArrayList<String>();
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);

while (rs.next()) {
tablesList.add(rs.getString(3));
}

if(!tablesList.contains("buyer_users"))
TableUtils.createTableIfNotExists(connectionSource, BuyerUser.class);

最佳答案

我今天在 OrmLite 4.48 和 PostgreSQL 9.1 上遇到了同样的问题。

我最后做了以下事情:

// create the table if it does not exist
if(!dao.isTableExists()) {
// use dao.isTableExists() first, as createTableIfNotExists() fails with postgreSQL 9.1 (OrmLite 4.48)
TableUtils.createTableIfNotExists(_pooledConnectionSrc, entityClass);
}

显然,这段代码假设您有兴趣创建相应的 DAO 实例。我做的,在我的项目中。要创建与您的表对应的 DAO,请参阅 DaoManager 类中的“createDao”方法。

(代码在 PgSQL 9.1 和 MySQL 5.5 上测试)

关于java - createTableIfNotExists 错误 - 关系已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26025405/

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