引言 因为之前没有相关经验,导致看视频理解写代码略有困难,
这将导致代码会很容易遗忘,毕竟不是自己写出来的,做个笔记加深印象
创建类及初始化 新建一个类,继承SQLiteOpenHelper
,重写onCreate
和onUpgrade
方法
添加基本配置信息 1 2 3 4 private static final String DB_NAME = "user.db" ;private static final String TABLE_NAME = "user_info" ;private static final int DB_VERSION = 1 ;
使用单例模式,将构造方法用private修饰,调用父类构造方法 1 private static UserDBHelper mHelper = null ;
1 2 3 4 5 private UserDBHelper (Context context) { super (context,DB_NAME,null ,DB_VERSION); }
获取对象实例的方法 1 2 3 4 5 6 7 8 9 10 11 12 13 public static UserDBHelper getInstance (Context context) { if (mHelper == null ) { mHelper = new UserDBHelper (context); } return mHelper; }
创建数据库后执行sql命令 1 2 3 4 5 6 7 8 9 10 11 12 13 @Override public void onCreate (SQLiteDatabase db) { String sql = "CREATE TABLE IF NOT EXISTS " +TABLE_NAME+" (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + " name VARCHAR NOT NULL," + " age INTEGER NOT NULL," + " height LONG NOT NULL," + " weight FLOAT NOT NULL," + " married INTEGER NOT NULL);" ; db.execSQL(sql); }
这样初始化好了
创建读写连接 添加变量 1 2 private SQLiteDatabase mRDB = null ;private SQLiteDatabase mWDB = null ;
读写连接方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public SQLiteDatabase openReadLink () { if (mRDB == null || !mRDB.isOpen()) { mRDB = mHelper.getReadableDatabase(); } return mRDB; } public SQLiteDatabase openWriteLink () { if (mWDB == null || !mWDB.isOpen()) { mWDB = mHelper.getWritableDatabase(); } return mWDB; }
关闭读写连接 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public void closeLink () { if (mRDB != null && mRDB.isOpen()) { mRDB.close(); mRDB = null ; } if (mWDB != null && mWDB.isOpen()) { mWDB.close(); mWDB = null ; } }
我感觉可以理解为关闭数据库,将数据库变量重置为null
写入的方法 自定义一个user类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class User { public int id; public String name; public int age; public long height; public double weight; public boolean married; public User () { } public User (String name, int age, long height, double weight, boolean married) { this .name = name; this .age = age; this .height = height; this .weight = weight; this .married = married; } @Override public String toString () { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", height=" + height + ", weight=" + weight + ", married=" + married + '}' ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 public long insert (User user) { ContentValues values = new ContentValues (); values.put("name" ,user.name); values.put("age" ,user.age); values.put("height" ,user.height); values.put("weight" ,user.weight); values.put("married" ,user.married); return mWDB.insert(TABLE_NAME,null ,values); }
写入(SqliteHelperActivity.java
) 初始化user
1 2 3 4 5 6 7 8 9 10 11 user = new User (name, Integer.parseInt(age), Long.parseLong(height), Double.parseDouble(weight), married); if (mHelper.insert(user) > 0 ){ ToastUtil.show(this ,"添加成功" ); }
结束语 没有jdbc基础感觉真的好难,希望坚持下去,背也得背下捏