这种方式也能实现数据库的基本操作,简单介绍:
第一步布局文件如下(代码简单,自己写吧):
package com.example.db1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class AccountDBHelper extends SQLiteOpenHelper{
public AccountDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context,"account.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql="create table account (_id integer primary key autoincrement,name varchar(20),money varchar(20))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
第三步:在MainActivity.java中执行数据库的操作(没写数据库操作类)
package com.example.db1;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db;
private AccountDBHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new AccountDBHelper(this,"account.db",null,1);
}
public void insert(View view)
{
//封装列和值的对象,类似于map的数据结构
//table 表名
//values 更新的列及其值
//whereClause更新的条件
//whereArgs条件的值
db=helper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("name", "if");
values.put("money","2000");
db.insert("account", null, values);
db.close();
}
public void query(View view)
{
db=helper.getReadableDatabase();
Cursor cursor = db.query("account",new String[]{"name","money"},"name= ?",new String[]{"if"}, null,null,null);
while(cursor.moveToNext()){
String name=cursor.getString(0);
String money = cursor.getString(1);
System.out.println("name="+name+";money="+money);
Toast.makeText(this,"name="+name+";money="+money,0).show();
}
cursor.close();
}
public void update(View view){
db=helper.getReadableDatabase();
//封装列和值的对象,类似于map的数据结构
ContentValues values = new ContentValues();
values.put("money","500000");
//table 表名
//values 更新的列及其值
//whereClause更新的条件
//whereArgs条件的值
db.update("account", values,"name=?",new String[]{"if"});
//数据库对象关闭
db.close();
}
public void delete(View view){
db=helper.getReadableDatabase();
//封装列和值的对象,类似于map的数据结构
//table 表名
//values 更新的列及其值
//whereClause更新的条件
//whereArgs条件的值
db.delete("account","name=?",new String[]{"if"});
//关闭数据库
db.close();
}
}