如果我们需要动态在 SQLite 中创建数据表,此时就需要判断该表在 SQLite 中是否存在。如果不存在,则可以动态创建该表。如果存在,则不创建,如果强制创建,会抛出表已经存在错误信息。
那么,我们要如何去实现判断某个表在 SQLite 数据库中是否存在?需要查询 SQLite 内置的 sqlite_master 表格,该表格结构如下图:

上图中,各个列的含义如下:
type 记录项目的类型,如:table(表格)、index(索引)、view(视图)、trigger(触发器)
name 记录项目的名称,如:表名、索引名等
tbl_name 记录所从属的表名,如索引所在的表名,对于表来说,该列就是表名本身
rootpage 记录项目在数据库页中存储的编号,对于视图和触发器,该列值为 0 或者 NULL
sql 记录创建该项目的 SQL 语句,如创建表格的 create table SQL 语句
通过 SQLite 的 Java JDBC 驱动查询在 sqlite_master 表格中是否存在 t_user 表格。代码如下:
package com.hxstrive.sqlite;
import java.sql.*;
/**
* 怎样判断某个表在 SQLite 中是否存在
* @author hxstrive.com 2022/9/26
*/
public class SqliteTableExist {
public static void main(String[] args) throws Exception {
new SqliteTableExist();
}
public SqliteTableExist() throws Exception {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 打开数据库
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:sqlite_studio.db");
System.out.println("Opened database successfully");
// 创建用户表
statement = connection.prepareStatement(
" select count(*) as table_count from sqlite_master " +
" where type='table' and name=?");
statement.setString(1, "t_user");
resultSet = statement.executeQuery();
if(resultSet.next()) {
int count = resultSet.getInt("table_count");
if(count > 0) {
System.out.println("t_user 表存在");
} else {
System.out.println("t_user 表不存在");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != resultSet) {
resultSet.close();
}
if(null != statement) {
statement.close();
}
if(null != connection) {
connection.close();
}
}
}
}运行示例,输出如下:
Opened database successfully t_user 表存在