0

How to check if table exist in sqlite using java.

I have used the code

 String sql = "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'COMPANY'";
 System.out.println("Sql Sqlite" + sql);
 int i = stmt.executeUpdate(sql);

Dont Know its correct or not, I'm new to sqlite please help.

CL.
  • 173,858
  • 17
  • 217
  • 259
Vikas Singh
  • 175
  • 5
  • 19
  • You're not updating anything, so why are you using `executeUpdate()`? – JonK Dec 09 '15 at 12:07
  • @augustoccesar This question is actually about how to run a query. – CL. Dec 09 '15 at 12:10
  • @CL. it makes sense... The question is not very clear, but I see your point. Removed the flag. – augustoccesar Dec 09 '15 at 12:11
  • @augustoccesar. I just want to check, if the given table exist or not. – Vikas Singh Dec 09 '15 at 12:15
  • @VikasSingh I see... I believe there is an answer for you question already on SO. The post that I marked as duplicated, there is some examples of how to do this. I believe the answer bellow is a link to the same post that I flagged, check it out :) – augustoccesar Dec 09 '15 at 12:19

1 Answers1

-1

I did not find any native methods in Sqlite to check if a table exists, but from the question below a way to do that is doing a select in the table.

StackOverflow question

Another way to do it in java I found here, but not sure if will work .

 String sql = "CREATE TABLE YOUR_TABLE " +
               "(id INTEGER not NULL, " +
               " first VARCHAR(255), " + 
               " last VARCHAR(255), " + 
               " age INTEGER, " + 
               " PRIMARY KEY ( id ))"; 
try{
  stmt.executeUpdate(sql);
}catch(Exception se){
  //the table already exists
  se.printStackTrace();
}
Community
  • 1
  • 1
diogojme
  • 2,309
  • 1
  • 19
  • 25
  • That answer is for Android, not JDBC. – CL. Dec 09 '15 at 12:25
  • @CL. Yes, you're right, I already edited my answer, hope this help. – diogojme Dec 09 '15 at 16:24
  • This question is not about creating a table. – CL. Dec 09 '15 at 17:22
  • @CL. The question is about check if an table exists, and a way to check that is trying to create the table again, you will get an exception if it exists, may it is not the best solution or is not the best practice but is a way to check if a table exists. – diogojme Dec 09 '15 at 17:39