Android之SQLite3命令行管理数据库
SQLite适合移动设备的数据存储,有处理速度快,占用资源少等优点,不需要安装部署,内嵌到程序中作为其一部分.http://www.sqlite.org/
SQLite的数据库文件位于/data/data/your-app-name/databases目录下.
使用数据库最基本就是增删改查操作.下面的示例是使用SQLite进行增删改查的操作.
我们需要一个辅助类继承SQLiteOpenHelper类
view plain
package com.sumq;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper{
public MySQLiteHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
/*
*当数据库被创建时,首次执行该方法
*一般将创建表等初始化操作放在该方法中执行
*/
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists user_info(id integer primary key,name varchar,vip integer)");
}
/*当版本升级时调用该函数
*参数一为要更新的数据库
*参数二传入老的版本号
*参数三传入新的版本号
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/*
*看需要,该方法在每次打开数据库时被调用
*/
@Override
public void onOpen(SQLiteDatabase db) {
// TODO Auto-generated method stub
super.onOpen(db);
}
}
view plain
package com.sumq;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
public class UISQLiteActivity extends Activity {
TextView tv;
MySQLiteHelper mySQLiteHelper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
mySQLiteHelper = new MySQLiteHelper(this, "test.db", null, 1);
insertAndUpdateData(mySQLiteHelper);
String result = queryData(mySQLiteHelper);
tv.setText("名字\t等级\t"+result);
}
private void insertAndUpdateData(MySQLiteHelper mySQLiteHelper){
//获取数据库对象
SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();
//第一种插入数据库的方法直接写sql语句
db.execSQL("insert into user_info(name,vip) values('user1',1)");
//第二种调用insert方法
ContentValues values = new ContentValues();
values.put("name", "user2");
values.put("vip", "2");
db.insert("user_info", null, values);
//更新level=2 的数据
values.clear();
values.put("name", "user2");
values.put("vip", "3");
db.update("user_info", values, "vip = ?", new String[]{"2"});
db.close();
}
private String queryData(MySQLiteHelper mySQLiteHelper){
String result ="";
SQLiteDatabase db = mySQLiteHelper.getReadableDatabase();
Cursor cursor = db.query("user_info", null, null, null, null, null, "id asc");
while (cursor.moveToNext()) {
result = result+cursor.getString(cursor.getColumnIndex("name"))+" ";
result = result+cursor.getInt(cursor.getColumnIndex("vip"))+" \n";
}
cursor.close();
db.close();
return result;
}
@Override
protected void onDestroy() {
补充:移动开发 , Android ,