android——SQLite数据库存储(操作)

时间:2024-07-03 12:37:14
 public class MyDatabaseHelper extends SQLiteOpenHelper {

     //把定义SQL建表语句成字符串常量

     //图书的详细信息
//ID、作者、价格、页数、书名
public static final String CREATE_BOOK = "create table Book("
+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)"; private Context mContext; //构造方法
public MyDatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
mContext = context;
} //建表
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext,"数据库创建成功", Toast.LENGTH_SHORT).show();
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
}

  目前数据库中有一个Book表,如果想要添加一个Category表,就需要对数据库进行升级,这时需要用到MyDatabaseHelper中的onUpgrade()方法。

  首先和Book表的建立一样需要先写好建表语句:

  create table Category (

    id integer primary key autoincrement

    category_name text

    category_code integer)

  修改后的代码如下:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    //把定义SQL建表语句成字符串常量

    //图书的详细信息
//ID、作者、价格、页数、书名
public static final String CREATE_BOOK = "create table Book("
+"id integer primary key autoincrement,"
+"author text,"
+"price real,"
+"pages integer,"
+"name text)"; //图书的分类
//图书的id、分类名、分类代码
public static final String CREATE_CATEGORY = "create table Category("
+ "id integer primary key autoincrement,"
+ "category_name text,"
+ "category_code inter)"; private Context mContext; //构造方法
public MyDatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
mContext = context;
} //建表
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"数据库创建成功", Toast.LENGTH_SHORT).show();
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
}

  在onUpgrade()方法中先使用drop语句如果已经存在Book表和Category表,就把两张表都删掉,因为数据库已经存在了,onCreate()方法怎么样都不会再执行的。

  然后在MainActivity修改代码:

 public class MainActivity extends AppCompatActivity {

     private MyDatabaseHelper dbHelper;

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //创建帮助类的实例
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2); //注册按钮
Button creatDatabase = (Button) findViewById(R.id.creat_database);
//按钮响应
creatDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dbHelper.getWritableDatabase();
}
});

  dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);把最后一个参数从之前的1改为2,再按下创建数据库就可完成升级。
  接下来完成数据库的添加、更新、删除、查询操作。
  先修改布局文件添加4个按钮:
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:id="@+id/creat_database"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="建立数据库"/> <Button
android:id="@+id/add_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加数据"/> <Button
android:id="@+id/updata_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="更新数据"/> <Button
android:id="@+id/delete_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删除数据"/> <Button
android:id="@+id/query_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查询数据"/>
</LinearLayout>

  在MainActivity中这样完成:

 public class MainActivity extends AppCompatActivity {

     private MyDatabaseHelper dbHelper;

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //创建帮助类的实例
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2); //注册按钮
Button creatDatabase = (Button) findViewById(R.id.creat_database);
Button adddata = (Button) findViewById(R.id.add_data);
Button updataData = (Button) findViewById(R.id.updata_data);
Button deleteData = (Button) findViewById(R.id.delete_data);
Button queryData = (Button) findViewById(R.id.query_data);
//按钮响应
creatDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dbHelper.getWritableDatabase();
}
}); //添加数据
adddata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
//第一条数据
values.put("name","The Da Vinci Code");
values.put("author","Dan Brown");
values.put("pages",45);
values.put("price",16.96);
db.insert("Book",null,values);
values.clear();
//第二条数据
values.put("name","The Lost symbol");
values.put("author","Dan Brown");
values.put("pages",510);
values.put("price",19.95);
db.insert("Book",null,values);
Toast.makeText(MainActivity.this,"添加数据成功",Toast.LENGTH_SHORT).show();
}
}); //更新数据
updataData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price",10.899);
db.update("Book", values, "name = ?",new String[] {"The Da Vinci Code"});
}
}); //删除数据
deleteData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book","pages > ?",new String[] {"500"});
}
}); //查询数据
queryData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book", null, null ,null, null, null, null );
if(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("MainActivity","book name is " + name);
Log.d("MainActivity","book auther is " + author);
Log.d("MainActivity","book pagesis " + pages);
Log.d("MainActivity","book price is " + price);
}
}
});
}
}

  添加数据:先使用dbHelper.getWritableDatabase()方法创建一个SQLiteDatabase的实例db,用于操作数据库,然后创键一个ContentValues的实例values,用来存放要添加的数据。然后是要values的put()方法将数据存入values中,再使用db的insert()方法将数据添加进数据库。然后使用clear()方法清空values再添加下一个数据。最后提醒添加成功。

  更新数据:一样使用dbHelper.getWritableDatabase()创建一个一个SQLiteDatabase的实例db,在创建一个values,将要更新的数据存放在values中,然后使用update()方法更新数据。第三个和第四个参数用于判断修改的是哪一行的数据。

  删除数据:使用delete()方法,第一个参数是想要操作的表名,第二个第三个指定操作的行。

  查询数据:将数据存放在cursor对象中,query()方法最短也要有7个参数,例如:(返回值)方法名:query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy),其中table指定想要查询的表名,columns指定查询的列名,selection指定where的约束条件,selectionArgs为where中的占位符提供具体的值,groupBy指定group by的列,having对group by后的结果进行约束,orderBy查询结果的排序方式。

  db.query("Book", null, null ,null, null, null, null );这样的用法表示将遍历整个Book表。

  然后使用cursor的moveToFirst方法将指针移到第一行,再一次向下移动实现遍历,再使用cursor.getColumnIndex()方法得到相应列的索引,通过getString、getInt、getDouble获得相应类型的数据,最后输出查询的结果。