How to determine whether a data table exists in the Database

Source: Internet
Author: User

You can query the meta data of a database to obtain the data table.

Public static Boolean doestableexist (string tablename) {<br/> connection con = NULL; <br/> hashset <string> set = new hashset <string> (); <br/> try {<br/> class. forname (databaseconnection. getdatabaseconnection (); <br/> con = drivermanager. getconnection (databasename. con); <br/> databasemetadata meta = con. getmetadata (); <br/> resultset res = meta. gettables (null, <br/> New String [] {"table"}); <br/> while (res. next () {<br/> set. add (res. getstring ("table_name"); <br/>}< br/> res. close (); <br/> con. close (); <br/>}catch (exception e) {<br/> system. err. println ("exception:" + E. getmessage (); <br/>}< br/> // system. out. println (SET); <br/> return set. contains (tablename. touppercase (); <br/>}

 

ReplaceDatabaseconnection. getdatabaseconnection ()
AndDatabasename. Con
You just need to connect to the database. Refer to another article on how to connect a local database: http://blog.csdn.net/autofei/archive/2010/05/24/5621274.aspx

 

Another method is to connect to the database and capture exceptions.

// Connection = new databaseconnection (databaseconnection. derby, "", "DB", "UNCC", "UNCC"); <br/> connection = new databaseconnection (databaseconnection. s, "localhost", "Postgres", <br/> "Postgres", "Postgres"); <br/> database = new database (connection ); </P> <p> // checks to see if database structure already exists <br/> Boolean exists = true; <br/> statement stmt = connection. getstatement (); <br/> try {<br/> stmt.exe cutequery ("select * From qgram"); <br/>} catch (exception E) {<br/> connection. rollback (); <br/> exists = false; <br/>} 

 

Reference: http://www.herongyang.com/jdbc/JDBC-ODBC-Flat-File-List-Tables.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.