资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Android应用中如何将数据插入到SQLite数据库-创新互联

Android应用中如何将数据插入到SQLite数据库?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联成立十载来,这条路我们正越走越好,积累了技术与客户资源,形成了良好的口碑。为客户提供网站设计制作、成都网站设计、网站策划、网页设计、域名注册、网络营销、VI设计、网站改版、漏洞修补等服务。网站是否美观、功能强大、用户体验好、性价比高、打开快等等,这些对于网站建设都非常重要,创新互联通过对建站技术性的掌握、对创意设计的研究为客户提供一站式互联网解决方案,携手广大客户,共同发展进步。

1、使用db.execSQL(sql)

这里是把要插入的数据拼接成可执行的sql语句,然后调用db.execSQL(sql)方法执行插入。

public void inertOrUpdateDateBatch(List sqls) { 
SQLiteDatabase db = getWritableDatabase(); 
db.beginTransaction(); 
try { 
for (String sql : sqls) { 
db.execSQL(sql); 
} 
// 设置事务标志为成功,当结束事务时就会提交事务 
db.setTransactionSuccessful(); 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
// 结束事务 
db.endTransaction(); 
db.close(); 
} 
}

2、使用db.insert("table_name", null, contentValues)

这里是把要插入的数据封装到ContentValues类中,然后调用db.insert()方法执行插入。

db.beginTransaction(); // 手动设置开始事务 
for (ContentValues v : list) { 
db.insert("bus_line_station", null, v); 
} 
db.setTransactionSuccessful(); // 设置事务处理成功,不设置会自动回滚不提交 
db.endTransaction(); // 处理完成 
db.close()

3、使用InsertHelper类

这个类在API 17中已经被废弃了

InsertHelper ih = new InsertHelper(db, "bus_line_station"); 
db.beginTransaction(); 
final int directColumnIndex = ih.getColumnIndex("direct"); 
final int lineNameColumnIndex = ih.getColumnIndex("line_name"); 
final int snoColumnIndex = ih.getColumnIndex("sno"); 
final int stationNameColumnIndex = ih.getColumnIndex("station_name"); 
try { 
for (Station s : busLines) { 
ih.prepareForInsert(); 
ih.bind(directColumnIndex, s.direct); 
ih.bind(lineNameColumnIndex, s.lineName); 
ih.bind(snoColumnIndex, s.sno); 
ih.bind(stationNameColumnIndex, s.stationName); 
ih.execute(); 
} 
db.setTransactionSuccessful(); 
} finally { 
ih.close(); 
db.endTransaction(); 
db.close(); 
}

4、使用SQLiteStatement

查看InsertHelper时,官方文档提示改类已经废弃,请使用SQLiteStatement

String sql = "insert into bus_line_station(direct,line_name,sno,station_name) values(?,?,?,?)"; 
SQLiteStatement stat = db.compileStatement(sql); 
db.beginTransaction(); 
for (Station line : busLines) { 
stat.bindLong(1, line.direct); 
stat.bindString(2, line.lineName); 
stat.bindLong(3, line.sno); 
stat.bindString(4, line.stationName); 
stat.executeInsert(); 
} 
db.setTransactionSuccessful(); 
db.endTransaction(); 
db.close();

第三种方法需要的时间最短,鉴于该类已经在API17中废弃,所以第四种方法应该是最优的方法。

看完上述内容,你们掌握Android应用中如何将数据插入到SQLite数据库的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网页题目:Android应用中如何将数据插入到SQLite数据库-创新互联
分享网址:http://cdkjz.cn/article/dpdhgh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220