I want to check wether a table named basestation exists in a MySQL table from a Java program using JDBC. My code is:

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
     //...
}

but although table basestations exists in my database it seems that my code never enters the first clause and always decides that table does not exist, causing naturally a table already exists in database SQL error when trying to create the table from the beginning.

有帮助吗?

解决方案

Not the best way to do it below.. But you could do the following:

Use JDBC to send the following statement:

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

Parse the jdbc result set.

That should return either 1 or 0. If the resulting count is 1, then the table exists, otherwise, it does not.

其他提示

I suspect your getTables() not returning anything here. As per getTables documentation Only table descriptions matching the catalog, schema, table name and type criteria are returned. In your case catalog and schema are null, which may not be correct (my guess), populate them with proper values.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top