3

I am using sqlite3 database in a java application. How to programmatically get names of all tables in the database? I have tried google and stackoverflow as well, and could NOT find a simple solution as yet. Here is the MySqli code I use with PHP, I am trying a similar approach in Java-Sqlite3

mysqli_select_db($conn, $database);
$res = mysqli_query($conn, "SHOW TABLES FROM " . $database . "");
while($cRow = mysqli_fetch_array($res, MYSQL_NUM)) {

    $namm=$cRow[0];


    $query = "SELECT COUNT(*) FROM " . $namm . "";
    $result = mysqli_query($conn,$query);
    $rows = mysqli_fetch_row($result);
    $namk = $rows[0];

    echo "<li type='square' style='margin-bottom:3px;'>" . $cRow[0] . " (" . $namk . ")</li>";
}
mysqli_close($conn);
2
  • SELECT * FROM sqlite_master WHERE ... Commented Jun 6, 2018 at 7:06
  • Where what? that is the issue. Commented Jun 7, 2018 at 4:45

2 Answers 2

8

You could use JDBC's built-in APIs for exploring the database metadata:

try (Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
    ResultSet rs = conn.getMetaData().getTables(null, null, null, null));
    while (rs.next()) {
        System.out.println(rs.getString("TABLE_NAME"));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
ArrayList<String> tableNames = new ArrayList<String>();

SqlHelper sqlHelper = new SqlHelper(this, "MYSQLITE.db", null, 1);
SQLiteDatabase sqliteDatabase = sqlHelper.getWritableDatabase();
Cursor cursor = sqliteDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
while(cursor.moveToNext()){
   String tableName = cursor.getString(0);
   if(tableName.equals("android_metadata")){     
     continue;
   }else{
      tableNames.add(tableName);
   }
 }

1 Comment

Thank you for the answer. But this snippet I already have and tried it 2 days back, it threw some error, I don't readily remember. Will try to dig it up and give a try again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.