一、新建数据库
1.新建数据库的类
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteDataBase extends SQLiteOpenHelper {
private static final String name = "android"; //数据库名称
private static final int version = 1; //数据库版本
public SQLiteDataBase(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//使用事务操作SQLite数据库
db.beginTransaction();
try{
db.execSQL("CREATE TABLE IF NOT EXISTS person (id integer primary key autoincrement, name varchar(20), age INTEGER)");
db.execSQL("CREATE TABLE IF NOT EXISTS perchase (buyid integer primary key autoincrement, name varchar(20), good varchar(20), num INTEGER)");
db.setTransactionSuccessful();
}finally{
db.endTransaction();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL("DROP TABLE IF EXISTS person");
db.execSQL("DROP TABLE IF EXISTS perchase");
}finally{
db.endTransaction();
}
onCreate(db);
}
}
2.新建数据库的代码:
SQLiteDataBase databaseHelper = new SQLiteDataBase(DatabaseOperation.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"翠云 ", 4});
db.close();
二、查看数据
SQLiteDataBase databaseHelper = new SQLiteDataBase(AllDatabase.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from person", null);
int num = cursor.getCount();
while (cursor.moveToNext()) {
int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始
String name = cursor.getString(1);//获取第二列的值
int age = cursor.getInt(2);//获取第三列的值
}
cursor.close();
db.close();
三、删除数据
SQLiteDataBase databaseHelper = new SQLiteDataBase(AllDatabase.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("delete from person where id = ?", new Object[]{id});
//db.delete("person","id=?",new String[]{"'+id+'"});
db.close();
四、插入数据
SQLiteDataBase databaseHelper = new SQLiteDataBase(InsertDatabase.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("insert into person(name, age) values(?, ?)",new Object[]{ str_name , int_age});
db.close();
五、查找数据
SQLiteDatabase db = (new SQLiteDataBase(SearchDatabase.this)).getReadableDatabase();
Cursor cursor = null;
cursor = db.rawQuery("select * from person where age = " + (Integer.parseInt(keyWord)),null);
while (cursor.moveToNext()) {
int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始
String name = cursor.getString(1);//获取第二列的值
int age = cursor.getInt(2);//获取第三列的值
}
cursor.close();
db.close();
六、更新数据
SQLiteDataBase databaseHelper = new SQLiteDataBase(UpdateDatabase.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("update person set name = ? , age = ? where id = ?",new Object[]{ str_name , int_age , id});
db.close();