1

我想basestation从使用 JDBC 的 Java 程序检查 MySQL 表中是否存在名为的表。我的代码是:

conn = DriverManager.getConnection(url, username, password);

DatabaseMetaData dbm = conn.getMetaData();

tables = dbm.getTables(null, null, "basestations", null);

if (tables.next())
{   
     //Table exists in database
     //...
}
else
{
     //Table does not exist
     //...
}

但是虽然表basestations存在于我的数据库中,但我的代码似乎从未进入第一个子句,并且总是确定该表不存在,因此table already exists in database在尝试从头开始创建表时自然会导致 SQL 错误。

4

2 回答 2

2

这不是最好的方法。但你可以做以下事情:

使用 JDBC 发送以下语句:

select count(*) from information_schema.tables where information_schema.table_schema='your_schema' and information_schema.table_name='basestations';

解析 jdbc 结果集。

这应该返回 1 或 0。如果结果计数为 1,则表存在,否则不存在。

于 2012-01-17T16:44:55.667 回答
-1

我怀疑你的 getTables() 没有在这里返回任何东西。根据 getTables 文档,仅返回与目录、模式、表名和类型标准匹配的表描述。在您的情况下,目录和架构为空,这可能不正确(我的猜测),用适当的值填充它们。

于 2012-01-17T16:35:09.247 回答