平常在做Android数据库操作时,都是用的execsql之个方法. 今天偶然发现了sqliteStatement这个类.让我想起了在做Java Web开发写JDBC的代码时Prestatement这个类.Prestatement不仅提高了效率,也解决了sql注入的问题.那在Android中的sqliteStatement,是否也会提高一些效率呢?
于是写了一个简单的测试,比较execsql和sqliteStatement的executeInsert方法插入1000条数据所需要的时间.都没有使用事物.
新建一个数据库和users表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
private
static
final
String DB_NAME =
"userdb"
;
final
int
DB_VERSION =
1
;
public
DBHelper(Context context) {
super
(context,DB_NAME,
null
,DB_VERSION);
}
@Override
void
onCreate(sqliteDatabase db) {
"(_id int PRIMARY KEY,name varchar,gender int,age int,phoneNumber varchar,address varchar)"
);
}
@Override
onUpgrade(sqliteDatabase db,153)!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-weight:bold!important; font-size:1em!important; min-height:inherit!important">int
oldVersion,monospace!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-size:1em!important; min-height:inherit!important"> newVersion) {
}
}
|
UserDao {
private
DBHelper dbHelper;
sqliteDatabase db;
StringBuffer sql_insert;
List<User> users;
UserDao(Context context){
this
.dbHelper =
DBHelper(context);
.db = dbHelper.getWritableDatabase();
sql_insert =
StringBuffer();
users =
ArrayList<User>();
//测试数据
for
(
i =
0
;i<
1000
;i++){
User user =
User();
user.setId(i);
user.setName(
"name"
+i);
user.setGender(
);
user.setAge(user.getRandomAge());
user.setPhoneNumber(
"13800138000"
);
user.setAddress(
"GuangDong ShenZhen No."
+i);
users.add(user);
}
}
/**
* @return 返回执行所需要的时间
*/
long
insertexecsql()
{
long
start=System.currentTimeMillis();
(User user:users){
Object[] bindArgs = {user.getName(),user.getGender(),user.getAge(),user.getPhoneNumber(),user.getAddress()};
}
end = System.currentTimeMillis();
return
end - start;
}
/**
* @return 返回执行所需要的时间
*/
insertStatement()
{
start = System.currentTimeMillis();
(User user:users){
statement.bindString(
5
}
end = System.currentTimeMillis();
end - start;
}
}
|