Android编程之数据库Sql编程实例分析
程序员文章站
2022-06-23 10:15:09
本文实例讲述了android编程之数据库sql编程实现方法。分享给大家供大家参考。具体分析如下:
android中安装轻量级数据库sqlite,现在测试数据库基本操作。...
本文实例讲述了android编程之数据库sql编程实现方法。分享给大家供大家参考。具体分析如下:
android中安装轻量级数据库sqlite,现在测试数据库基本操作。
数据库基本操作:创建表,插入,删除可以用execsql();读取可以用rawquery();这两个函数都可以标准sql语句进行操作。
源代码:
package com.test.sql; import android.app.activity; import android.content.context; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; import android.os.bundle; import android.util.log; public class test_sql extends activity { databasehelper mopenhelper; private static final string database_name = "test.db"; private static final int database_version = 1; private static class databasehelper extends sqliteopenhelper { databasehelper(context context) { super(context, database_name, null, database_version); } @override public void oncreate(sqlitedatabase db) { //新建一个用户表 //共有5项:id pwd name onlinetime level db.execsql("create table user_table ('id' int,'pwd' varchar,'name' varchar,'onlinetime' int,'level' int)"); } @override public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { } } /** called when the activity is first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); mopenhelper = new databasehelper(this); sqlitedatabase db = mopenhelper.getwritabledatabase(); //清空数据 db.execsql("delete from user_table"); //插入数据10000 123456 "jdh" 0 0 //插入数据10001 123456 "jim" 0 0 db.execsql("insert into user_table values (?,?,?,?,?)", new object[]{10000,"123456","jdh",0,0}); db.execsql("insert into user_table values (?,?,?,?,?)", new object[]{10001,"123456","jim",0,0}); //读取数据 cursor cursor = db.rawquery("select * from user_table where name = ?",new string[]{"jdh"}); while (cursor.movetonext()) { string str = cursor.getint(0) + cursor.getstring(1) + cursor.getstring(2) + cursor.getint(3) + cursor.getint(4); log.i("str:", str); } } }
希望本文所述对大家的android程序设计有所帮助。