新建Dao类来操作数据库的增删改查
package com.example.mysqlite;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
// 操作数据增删改查
public class Dao {
private final DatabaseHelper mhelper;// 定义DatabaseHelper类
private final static String TAG = "DAO";
public Dao(Context context){// 构造方法
mhelper = new DatabaseHelper(context);
}
(一)增加某一行数据用“insert into”
public void insert(){
SQLiteDatabase db = mhelper.getReadableDatabase();
// values后使用占位符,防止sql注入
String sql = "insert into "+Constant.TABLE_NAME+"(_id,name,age,score,phone,address) values(?,?,?,?,?,?)";
db.execSQL(sql,new Object[]{1,"LIU",20,90,123456,"CN"});// 增加的数据放入Object对象
db.close();// 关闭数据库
}
(二)删除某一行数据用“delete from”,用where来设置删除条件
public void delete(){
SQLiteDatabase db = mhelper.getReadableDatabase();
String sql = "delete from "+Constant.TABLE_NAME+" where name = l12 ";
db.execSQL(sql);
db.close();
}
(三)更改某行数据用“update”,set重设某个属性值,where设置更改条件
public void update(){
SQLiteDatabase db = mhelper.getReadableDatabase();
String sql = "update "+Constant.TABLE_NAME+" set age = 24 where name = LIU ";
db.execSQL(sql);
db.close();
}
(四)查询某条数据用“select",但execSQL没有返回值,换用rawQuery方法,返回查询得到的游标。
public void query(){
SQLiteDatabase db = mhelper.getReadableDatabase();
// String sql = "select * from "+Constant.TABLE_NAME+" where name = lcz ";//可通过where设置查询条件
String sql = "select * from "+Constant.TABLE_NAME;
Cursor cursor = db.rawQuery(sql,null);
while (cursor.moveToNext()){ // moveToNext说明还有数据,假设有下一行
int index = cursor.getColumnIndex("name");// 获取属性值为“name”的列的索引值
String name = cursor.getColumnName(index);// 获取索引值为index的列的字符串内容
Log.d(TAG, "name ="+name);
}
cursor.close();// Cursor是种资源,不用需关闭
db.close();
}
}