与数据库的连接
创建数据库
1.创建一个类继承SQLiteOpenHelper类
2.实现里面的方法,创建构造方法
1 public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
2 super(context, name, null, version);
3 mContext=context;
4 }
参数解释:
context:上下文
name:数据库名称,常定义为常量
factory:游标工厂
version:版本号
3.创建子类对象,再调用getReadableDatabase()/getWritableDatabase()方法
DatabaseHelper文件:
1 package com.example.keep; 2 3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteOpenHelper; 6 import android.util.Log; 7 8 import androidx.annotation.Nullable; 9 public class DatabaseHelper extends SQLiteOpenHelper { 10 private static final String TAG="DatabaseHelper"; 11 public DatabaseHelper(@Nullable Context context) { 12 super(context, Constants.DATABASE_NAME, null, Constants.VERSION_CODE); 13 } 14 15 @Override 16 public void onCreate(SQLiteDatabase db) { 17 //创建时的回调 18 Log.d(TAG,"创建数据库..."); 19 String sql="create table "+Constants.TABLE_NAME+" (id integer primary key autoincrement, in_out varchar,money float,date varchar,type varchar,way varchar)"; 20 db.execSQL(sql); 21 } 22 23 @Override 24 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 25 //升级时的回调 26 Log.d(TAG,"升级数据库..."); 27 } 28 }
constants文件:
1 public class Constants { 2 public static final String DATABASE_NAME="money_keep.db"; 3 public static final int VERSION_CODE=1; 4 public static final String TABLE_NAME="KeepUser"; 5 }
子类中使用: