sqlite是android提供的一个本地小型数据库,方便易用,但不宜过度依赖。
使用
SQLiteDatabase db
定义一个数据库对象db,但是需要自习实现一个SQLiteOpenHelper类,文档是这么定义 SQLiteOpenHelper的
A helper class to manage database creation and version management.
下面自己定义一个Dbhelper类,并复写内部方法(from mars )
public class DbHelper extends SQLiteOpenHelper {
private static final int VERSION=1;
public DbHelper(Context context,String name,CursorFactory cursorFactory,int version)
{
super(context, name, cursorFactory, version);//调用父类的构造方法
}
public DbHelper(Context context,String name,int version)
{
this(context,name,null,version);
}
public DbHelper(Context context,String name)
{
this(context, name,VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql="create table user(id int ,name varchar(20))";//构造表结构
db.execSQL(sql) //发送创建表语句
System.out.println("create success");//测试语句
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
System.out.println("updata success~");//测试语句
}
}
在后面每次需要使用数据库的时候都要这么写
DbHelper dbHelper= new DbHelper(SqliteActivity.this,"zhou_s_db");
SQLiteDatabase db=dbHelper.getReadableDatabase();
db是一个数据库中某一个表的对象,可以使用这个对象进行各种数据库的操作。
使用Dbhelper更新数据库版本号
DbHelper dbHelper=new DbHelper(SqliteActivity.this,"zhou_s_db",2);
从输入框是得到用户输入并插入数据库,需要借助ContentValues对象来完成
insertNameString=myEditText.getText().toString();//得到用户输入字符串
ContentValues content = new ContentValues();//生成一个ContentValues对象
content.put("id", 1); //put函数接受一对键值对,键对应数据库表中的列名称
content.put("name", insertNameString);
DbHelper dbHelper = new DbHelper(SqliteActivity.this, "zhou_s_db");
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.insert("user", null, content); //数据库对象插入操作,
Toast.makeText(SqliteActivity.this, "Insert Success!", Toast.LENGTH_SHORT).show(); //提示用户操作成功
更新数据库已存在的信息
db.update("user", content, "id=?", new String[]{"1"});
其中content中已put 了对应表的列名称的需要更新的值,参考上一例
使用db对象查询数据库,需要一个Curson对象得到db.query返回的对象引用
参数表如下
Cursor cursor=db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
实例
Cursor cursor=db.query("user", new String[]{"id","name"}, "id=?", new String[]{"1"}, null, null, null);
while (cursor.moveToNext()) {
result+=cursor.getString(cursor.getColumnIndex("name"))+"\n";
}
System.out.println("query success!!!");
myView.setText(result);
删除操作:delete(String table, String whereClause, String[] whereArgs)
delString=myEditText.getText().toString();
db.delete("user", "id=?", new String[]{"1"});
Toast.makeText(SqliteActivity.this, "Delete Success!", Toast.LENGTH_SHORT).show();