SQL语句实现
一:创建数据库
首先我们得创建一个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