Apache Derby - 检查数据库是否已创建?
将 Apache Derby 与 Java(J2ME,但我不认为这有什么区别)一起使用,是否有任何方法可以检查数据库是否已存在并包含表?
Using Apache Derby with Java (J2ME, but I don't think that makes a difference) is there any way of checking if a database already exists and contains a table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,除了很少的解决办法之外,没有任何解决方案,不像 MySQL,我们有 IF EXIST 的功能。
您要做的就是尝试连接到数据库,如果无法连接,则可能是数据库不存在。 连接成功后,您可以执行一个简单的选择,例如 SELECT count(*) FROM TABLE_NAME,以了解该表是否存在。 您将依赖于例外情况。 即使在 Sun 的官方示例中,我也看到了类似的工作。
在 Oracle 中,我们有字典表来了解数据库对象。 我怀疑我们在德比是否有类似的事情。
[已编辑]
嗯,我发现有一种方法可以知道该表是否存在。 尝试从 SYSTABLES 中选择表名。 它用于检查表是否存在,为了检查数据库,您可能需要做类似的事情,我在上面解释过。
I know of none, except few work around, unlike MySQL where we have that facility of IF EXIST.
What you do is, try to connect to the database, if couldn't its likely its not there. And after a successful connection, you can do a simple select, like SELECT count(*) FROM TABLE_NAME, to know whether the table exist or not. You would be depending on the exception. Even in an official example from Sun, I have seen the similar work around.
In Oracle we have dictionary tables to know about the database objects. I doubt if we have anything like that in Derby.
[Edited]
Well, I found that there is a way to know if the table exist. Try, SELECT tablename FROM SYSTABLES. It is for checking the existence of a table, for checking database you may need to do similar thing, I explained above.
Adeel,您也可以使用Connection.getMetaData 返回 DatabaseMetaData 对象,然后使用 getTables,当然,一旦您连接到数据库。 这样做的优点是可以适用于任何具有值得信赖的 JDBC 驱动程序的数据库。
为了检查数据库是否存在,如果您以嵌入式方式使用Derby,或者服务器位于同一台计算机上,则可以检查数据库的文件夹是否存在。 虽然有点笨拙。 我会按照 Adeel 的建议进行操作并尝试连接,如果异常不存在则捕获异常。
Adeel, you could also use Connection.getMetaData to return a DatabaseMetaData object, then use the getTables, once you have the connection to the database of course. This has the advantage of working for any database with a JDBC driver worth it's salt.
For checking if the database exists, if you are using Derby in the embedded way, or the server is on the same machine, you could check if the folder for the database exists. Is a bit kludgy though. I would do as Adeel suggests and try to connect, catching the exception if it's not there.
我建议获取 DatabaseMetaData 对象,然后使用其中的 getTables(null, null, null, new String[]{"TABLE"}) 方法,该方法返回一个 ResultSet。 使用 ResultSet 的 next() 方法(返回一个布尔值)来测试是否存在任何表。 如果测试为真,则表已存在。 错误,数据库为空。
I would suggest getting the DatabaseMetaData object, then using the getTables(null, null, null, new String[]{"TABLE"}) method from it, which returns a ResultSet. Use the next() method of the ResultSet, which returns a boolean, to test if any tables exist. If it tests true, you have tables in existence. False, and the database is empty.