sqlite的使用
1.创建一个类继承SQLiteOpenHelper并重写父类的onCreate()方法,添加一个构造方法。在onCreate方法中编写创建表的语句。
public class DatabaseHelper extends SQLiteOpenHelper { public static final String PRODUCT_TABLE_NAME = "productNotupload"; public static final String USERNAME = "username"; public static final String PRODUCTNAME= "product_name"; public static final String RECORDTIME = "transact_date"; public static final String FILEPATH = "filepath"; public static final String TRADENO = "tradeno"; public static final String DATABASE_NAME = "jingan.db"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + PRODUCT_TABLE_NAME + "(" + USERNAME + " varchar(20) not null, " + PRODUCTNAME + " varchar(60) not null," + RECORDTIME + " varchar(20) not null," + FILEPATH + " varchar(200) not null," + TRADENO + " varchar(20) not null )"); }
2. 使用:在需要使用该表时,先初始化数据库对象得到操作权限,从而进行insert,delete , update,query操作。
DatabaseHelper databaseHelper = new DatabaseHelper(this); //获取数据库对象 mSqLiteDatabase = databaseHelper.getWritableDatabase(); //获取写权限 //添加 insert ContentValues contentValues = new ContentValues(); contentValues.put(DatabaseHelper.USERNAME, username); contentValues.put(DatabaseHelper.PRODUCTNAME, productName); contentValues.put(DatabaseHelper.RECORDTIME, recordTime); contentValues.put(DatabaseHelper.FILEPATH, filepath); contentValues.put(DatabaseHelper.TRADENO, tradeno); mSqLiteDatabase.insert(DatabaseHelper.PRODUCT_TABLE_NAME, null, contentValues); //删除 delete mSqLiteDatabase.delete(DatabaseHelper.PRODUCT_TABLE_NAME, whereClauseString, whereArgsString); //查询 query Cursor cursor = mSqLiteDatabase.query(DatabaseHelper.PRODUCT_TABLE_NAME, columns, null, null, null, null, null); while (cursor.moveToNext()) { String userName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.USERNAME)); String productName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.PRODUCTNAME)); String recordTime = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.RECORDTIME)); String filepath = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.FILEPATH)); String tradeno = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.TRADENO)); UnVerifyModel unVerifyModel = new UnVerifyModel(userName,productName,recordTime,filepath,tradeno); lists.add(unVerifyModel); Log.e("-----------------------", ":" + userName + "|" + productName + "|" + recordTime + "|" + filepath + "|" + tradeno + "/n"); }