gpt4 book ai didi

android - 使用 SQLiteDatabase.execSQL 执行多个语句

转载 作者:IT老高 更新时间:2023-10-28 21:34:42 24 4
gpt4 key购买 nike

我按照标准教程使用 Android 构建数据库。我创建了一个名为 DbHelper 的类,它扩展了 SQLiteOpenHelper。我已经重写了创建处理程序来执行一个字符串。

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DbDefinitions.DB_CREATE);
}

DbDefinitions.DB_CREATE 是我创建的静态字符串。

public static final String TABLE_MESSAGES = "messages";
public static final String TABLE_FRIENDS = "friends";

public static final String STATE_OK = "STATE_OK";

public static final String DB_CREATE =
"create table " + TABLE_MESSAGES + " (_id integer primary key, user_id integer not null, created_on integer, subject text not null, summary text not null, messagetext text null, read integer not null, status text not null default '" + STATE_OK + "'); " +
"create table " + TABLE_FRIENDS + " (_id integer primary key, user_id integer not null, friend_id integer not null, created_on integer, status text not null default '" + STATE_OK + "');";

我想使用 1 个字符串来执行多个 SQL 语句。由于 SQLiteDatabase.execSQL 只允许 1 条语句,我该怎么做?

最佳答案

使用 Android 自带的标准方法无法做到这一点。因此,如果您想执行 batch 多个 SQL 语句,则必须创建自己的实用程序来执行此操作。例如,你可以有这样的东西:

public void executeBatchSql(String sql){
// use something like StringTokenizer to separate sql statements
for each sql statement{
database.execSQL(oneStatement);
}
}

不过,我会做的是这样的:

String sql1 = "create bla bla bla;";
String sql2 = "create foo bar;";
String[] statements = new String[]{sql1, sql2};

// then
for(String sql : statements){
database.execSQL(sql);
}

关于android - 使用 SQLiteDatabase.execSQL 执行多个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com