And*_*rew 37 database sqlite android
我遵循了使用Android构建数据库的标准教程.我创建了一个名为DbHelper的类,它扩展了SQLiteOpenHelper.我已重写创建处理程序以执行字符串.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DbDefinitions.DB_CREATE);
}
Run Code Online (Sandbox Code Playgroud)
DbDefinitions.DB_CREATE是我创建的静态String.
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 + "');";
Run Code Online (Sandbox Code Playgroud)
我想使用1 String来执行多个SQL语句.我怎么能这样做,因为SQLiteDatabase.execSQL只允许1个语句?
Cri*_*ian 40
使用Android附带的标准方法是不可能的.因此,如果要执行多个SQL语句批处理,则必须创建自己的实用程序才能执行此操作.例如,你可以这样:
public void executeBatchSql(String sql){
// use something like StringTokenizer to separate sql statements
for each sql statement{
database.execSQL(oneStatement);
}
}
Run Code Online (Sandbox Code Playgroud)
虽然,我做的是这样的:
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);
}
Run Code Online (Sandbox Code Playgroud)
fro*_*ous 19
好吧,在我的情况下,我从一个文件中删除查询,我保存为资产这是我使用的解决方案+ -
String script = readAsset(CREATE_SCRIPT);//readAsset is a method i use to get the file contents
try {
String[] queries = script.split(";");
for(String query : queries){
db.execSQL(query);
}
} catch (Exception e) {
.....
Run Code Online (Sandbox Code Playgroud)
编辑
在我的例子中,查询是我完全控制的简单插入查询.但是,有关";"的查询的问题已经提出 在他们里面.
@TWiStErRob建议使用
script.split(";$");// $ meaning end of line. You will need to use RegexOption.MULTILINE for this to work
Run Code Online (Sandbox Code Playgroud)
要么
script.split(";\n");// but you will need to ensure that each query is on a different line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35584 次 |
| 最近记录: |