首先我们得创建一个java类继承SQLiteOpenHelper,用来创建数据库的具体实现
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {//建表
//用来创建一个student的表
String sql="create table student(id integer primary key autoincrement,stuid varchar(20),stuname varchar(20),stuclass varchar(20))";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
然后通过在MainActivity里面new一个这样的对象,来创建一个数据库,这里创建student.db数据库
MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(this,"student.db",null,1);
final SQLiteDatabase sqLiteDatabase= mySQLiteOpenHelper.getWritableDatabase();
在这里使用Google的一个工具(需要其他special工具),如果没有,推荐看这篇超级厉害的博客,俺老师的哈哈~
首先在build里面添加依赖,不要忘记点右上角的sync now
implementation 'com.facebook.stetho:stetho:1.5.1'
然后在需要进行数据库操作的Mainactivity的oncreate函数里面添加下面代码
Stetho.initializeWithDefaults(this);
chrome://inspect/#devices
然后你需要运行模拟器,然后刷新页面,会出现下面的页面
如果你拥有special的工具,那么点击inspect 会出现下面的情况
数据库在这里,俺这里已经做过一些插入数据的操作了
在监听器里面进行数据操作,通过点击按钮实现增删改查,有2种方式,以插入为例:
一:直接写SQL语句
sqLiteDatabase.execSQL("insert into values()");
二:使用参数代入
ContentValues contentValues=new ContentValues();
contentValues.put("字段名","value");
sqLiteDatabase.insert("表",null,contentValues);
在这里使用参数可变的方式
Button button=findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("username","admin");
contentValues.put("password","123456");
contentValues.put("age",288);
sqLiteDatabase.insert("user",null,contentValues);
sqLiteDatabase.delete("user","id=?",new String[]{"2"});
sqLiteDatabase.update("user",contentValues,"id=?",new String[]{"1"});
}
Button button=findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues contentValues=new ContentValues();
contentValues.put("username","admin");
contentValues.put("password","123456");
contentValues.put("age",288);
sqLiteDatabase.update("user",contentValues,"id=?",new String[]{"1"});
}
用游标进行遍历数据,调用方法query使用7个参数,分别代表 表,列,查询的条件,查询的参数,groupby,having,orderby的7个参数,null表示全部,不做特别指定
Cursor cursor=sqLiteDatabase.query("user",null,"username=?",new String[]{"admin"},null,null,null);
while (cursor.moveToNext()){
int id=cursor.getInt(0);//获得数据
String username=cursor.getString(1);
String passwd=cursor.getString(2);
int age=cursor.getInt(3);
Log.i("Mainactivity", "id "+id+"username"+username+"age"+age);//打印日志
}
cursor.close();//关闭游标,防止内存泄漏
以删除ID为2为例
Button button=findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sqLiteDatabase.delete("user","id=?",new String[]{"2"});
}
首先得引入框架依赖,见博客
此参照学习我的无敌的老师的6666的博客
新添加权限
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
新建一个java类用来数据库的映射,用来建表(这个类相当于一个表,类里面的变量就是字段名),实现注解为后文做准备
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
@Table(name = "user")//注解
public class User {
@Column(name = "id", isId = true)
private int id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "age")
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
然后在操作数据库的Mainactivity里加入以下代码
DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
.setDbName("test.db")
// 不设置dbDir时, 默认存储在app的私有目录.
// .setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
.setDbVersion(2)
.setDbOpenListener(new DbManager.DbOpenListener() {
@Override
public void onDbOpened(DbManager db) {
// 开启WAL, 对写入加速提升巨大
db.getDatabase().enableWriteAheadLogging();
}
})
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
// TODO: ...
// db.addColumn(...);
// db.dropTable(...);
// ...
// or
// db.dropDb();
}
});
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DbManager db = null;
try {
db = x.getDb(daoConfig);
User user = new User();//new 一个对象,相当于是表中的一行,相当于一条记录
//相当于插入数据
user.setUsername("test"+System.currentTimeMillis());
user.setPassword("passwd");
user.setAge(30);
db.save(user);//写入数据,保存到数据库
} catch (DbException e) {
e.printStackTrace();
return;
}
}
});
DbManager db = null;
try {
db = x.getDb(daoConfig);
User user = new User();
user.setId(2);
db.delete(user);
} catch (DbException e) {
e.printStackTrace();
return;
}
//条件删除
DbManager db = null;
try {
db = x.getDb(daoConfig);
db.delete(User.class,
WhereBuilder.b("username", "=", "test"));
} catch (DbException e) {
e.printStackTrace();
return;
}
try {
DbManager db = null;
db = x.getDb(daoConfig);
User user = new User();
user.setId(1);
user.setUsername("new user");
user.setPassword("new passwd");
user.setAge(30);
db.saveOrUpdate(user);
} catch (DbException e) {
e.printStackTrace();
return;
}
//条件更新
try {
DbManager db = null;
db = x.getDb(daoConfig);
db.update(User.class, WhereBuilder.b("username", "=", "test"),
// WhereBuilder.b("id", "=", 1).and("isAdmin", "=", true).,
new KeyValue("username", "test_name"), new KeyValue("password", "new pss"));
} catch (DbException e) {
e.printStackTrace();
return;
}
DbManager db = null;
try {// 删除1
db = x.getDb(daoConfig);
List<User> users = new ArrayList<>();
users= db.selector(User.class).orderBy("id", true).limit(1000).where("username","=","test").findAll();
// users= db.selector(User.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).findAll();
for (User user : users){
Log.i("testdb","test" + user);
}
} catch (DbException e) {
e.printStackTrace();
return;
}