(1)自定义一个类继承SQLiteOpenHelper
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context) {
/**
* name 数据库的名字
* factory 游标工厂
* version 版本
*/
super(context, "Account.db", null, 1);
}
/**
* Called when the database is created for the first time
* 当数据库第一次 创建的时候调用 那么这个方法特别适合做 表结构的初始化
*
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),money varchar(20))");
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"张三","5000"});
db.execSQL("insert into info(name,money) values(?,?)", new String[]{"李四","3000"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
(2)实例化该类,并调用getWritableDatabase()方法得到数据库对象。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyOpenHelper helper = new MyOpenHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
//需求把张三和李四的数据取出来
Cursor cursor = db.query("info", null, null, null, null, null, null);
if (cursor!=null&&cursor.getCount()>0) {
while(cursor.moveToNext()){
String name = cursor.getString(1);
String money = cursor.getString(2);
System.out.println("name:"+name+"-----"+money);
}
cursor.close();
}
}
}