创建SQLite需要实现的方法
创建一个类继承SQLiteOpenHelper``
public class MySqlLiteHelp extends SQLiteOpenHelper {
public MySqlLiteHelp( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
实现里面的两个方法
onCreate创建数据库创建表用
onUpgrade用于数据库更新
//创建数据库中的表创建
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table user(id integer,name varchar(20))");
db.beginTransaction();
for (int i = 0; i < 100; i++) {
db.execSQL("insert into user values(?,?)",new Object[]{i,"小赚风"+i});
}
db.setTransactionSuccessful();
db.endTransaction();
}
//用于数据库的更新
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
使用那个表和打开SQLite连接的方法
private MySqlLiteHelp mySqlLiteHelp;
private SQLiteDatabase db;
mySqlLiteHelp = new MySqlLiteHelp(this,"user.db",null,1);
db = mySqlLiteHelp.getReadableDatabase();
系统提供的,增,删,改,查,方法
> 这是查询方法
Cursor cursor = db.query("user", null, null, null, null, null, null);
if(cursor!=null){
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Toast.makeText(this,id+ "-"+name, Toast.LENGTH_SHORT).show();
}
}
> 这是添加方法
ContentValues contentValues = new ContentValues();
contentValues.put("id",17);
contentValues.put("name","呵呵");
db.insert("user",null,contentValues);
> 删除方法
db.delete("user","id = ?",new String[]{"18"});
> 修改方法
ContentValues contentValues = new ContentValues();
contentValues.put("name","名字");
db.update("user",contentValues,"id = ?",new String[]{"18"});
原生的,增,删,改,查,方法
> 这是查询
String sql = "select * from user ";
Cursor cursor1 = db.rawQuery(sql, new String[]{});
if(cursor1!=null){
while (cursor1.moveToNext()){
int id = cursor1.getInt(cursor1.getColumnIndex("id"));
String name = cursor1.getString(cursor1.getColumnIndex("name"));
Toast.makeText(this,id+ "-"+name, Toast.LENGTH_SHORT).show();
}
}
> 这是修改
String sql = "update user set name = ? where id = ?";
db.execSQL(sql,new Object[]{"北京",18});
> 这是添加
String sql = "insert into user(id,name) values(?,?)";
db.execSQL(sql,new Object[]{18,"小赚风"});
> 这是删除
String sql = "delete from user where id = ?";
db.execSQL(sql,new Object[]{18});