作者:mysrain3 | 来源:互联网 | 2023-09-05 18:50
上一篇已经讲到如何使用adb查询表结构的建立接下来就介绍实现的几中操作SQLite数据库简介ACID;数据库事物正确执行的4个基本要素:1:原子性2:一致性3:隔离性4:持久性数据的常用操作主要有以
上一篇已经讲到如何使用adb查询表结构的建立 接下来就介绍实现的几中操作
SQLite数据库简介
ACID;数据库事物正确执行的4个基本要素:
1:原子性2:一致性3:隔离性4:持久性
数据的常用操作主要有以下:
1、创建数据库:
2、添加数据库
public void addData(View view){
SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
ContentValues cOntentValues=new ContentValues();//封装数据
//开始组装第一条数据
contentValues.put("name","Java");
contentValues.put("author","孙卫琴");
contentValues.put("pages","500");
contentValues.put("price","56.5");
sqLiteDatabase.insert("book","name",contentValues);
//insert into book(name) values(null);
contentValues.put("name","c++");
contentValues.put("author","Dan");
contentValues.put("pages","400");
contentValues.put("price","56");
sqLiteDatabase.insert("book","name",contentValues);
}
3、删除数据
public void deleteData(View view){
SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
sqLiteDatabase.delete("book","pages",new String[]{"500"});
}
4、更新数据
public void queryData(View view){
StringBuilder stringBuilder=new StringBuilder();
SQLiteDatabase sqLiteDatabase=dbHelper.getWritableDatabase();
Cursor cursor=sqLiteDatabase.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
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"));
stringBuilder.append(name+"-"+author+"-"+pages+"-"+price+"\n");
}while(cursor.moveToNext());
}
在DBhelper类中
package cn.edu.bzu.sqlapplication.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DBHelper extends SQLiteOpenHelper{//vesion 数据库名称
private Context context;
public static final String DB_NAME="BookStore.db";
public static final String CREATE_BOOK="create table book(id integer primary key autoincrement,author text,price real,pages integer,name text)";
public static final String CREATE_CATEGORY="create table category(id integer primary key autoincrement,name text, code integer)";
public DBHelper(Context context,int version) {
super(context,DB_NAME,null, version);
Log.d("DBHelper","constructor");
this.cOntext=context;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("DBHelper","onCreate");
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(context,"create succeeded",Toast.LENGTH_LONG).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);
}
}