执行与SQLiteDatabase.execSQL多条语句多条、语句、SQLiteDatabase、execSQL

2023-09-03 21:44:22 作者:怪力

我已经按照标准教程建库与Android。我已经创建了一个名为DbHelper它扩展SQLiteOpenHelper。我已经覆盖了创建处理程序来执行的字符串。

I've followed a standard tutorial for building a database with Android. I've created a class called DbHelper which extends SQLiteOpenHelper. I've Overridden the create handler to execute a string.

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

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

DbDefinitions.DB_CREATE is a static String I've created.

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语句?

I'd like to use 1 String to execute multiple SQL statements. How can I do this as SQLiteDatabase.execSQL only allows 1 statement?

推荐答案

这是不可能使用它自带了Android标准的方法做。所以,如果要执行多个SQL语句的批的,你必须创建自己的工具来做到这一点。例如,你可以有这样的事情:

That's not possible to do using the standard methods which comes with Android. So, if you want to execute batch of multiple SQL statements, you will have to create your own utility to do so. For instance, you can have something like this:

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

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

Though, what I'd do is something like this:

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);
}