第一步、数据库初始化
继承 SQLiteOpenHelper,初始化数据库
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context) {
super(context, "itheima.db", null,4);
}
/**
* Called when the database is created for the first time.
* 当数据库第一次创建的时候调用
* 那么这个方法特别适合做表结构的初始化 创建表就是写sql语句
*/
@Override
public void onCreate(SQLiteDatabase db) {
//id 一般以_id
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20),phone varchar(20))");
}
/**
* Called when the database needs to be upgraded
* 当数据库版本升级的时候调用
* 这个方法适合做 表结构的更新
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table info add phone varchar(20)");
}
}
第二步、数据库的增删改查
public class MainActivity extends Activity {
private MyOpenHelper myOpenHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOpenHelper = new MyOpenHelper(getApplicationContext());
//打开或者创建数据库 如果是第一次就是创建
// SQLiteDatabase sqLiteDatabase = myOpenHelper.getWritableDatabase();
//打开或者创建数据库 如果是第一次就是创建 如果磁盘满了 返回只读的
// SQLiteDatabase readableDatabase = myOpenHelper.getReadableDatabase();
}
//点击按钮增加一条记录
public void click1(View v){
//[1]获取数据库对象
SQLiteDatabase db = myOpenHelper.getWritableDatabase();
//[2]执行增加一条的sql语句
db.execSQL("insert into info(name,phone) values(?,?)", new Object[]{"张三","1388888"});
//[3]数据库用完需要关闭
db.close();
}
//删除
public void click2(View v){
SQLiteDatabase db = myOpenHelper.getWritableDatabase();
db.execSQL("delete from info where name=?", new Object[]{"张三"});
db.close();
}
//更新
public void click3(View v){
SQLiteDatabase db = myOpenHelper.getWritableDatabase();
db.execSQL("update info set phone=? where name=? ", new Object[]{"138888888","张三"});
db.close();
}
//查找
public void click4(View v){
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from info", null);
if (cursor!= null&&cursor.getCount()>0) {
while(cursor.moveToNext()){
//columnIndex代表列的索引
String name = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println("name:"+name+"----"+phone);
}}}}
网友评论