测试类
package cn.mf.cts.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; /** * CopyRright (c)2018-2028: chanpinxue.cn * Project: cts * Module Name: SQLiteDBUtil * Comments: SQLite测试类 * JDK version used: JDK1.8 * Author: jzh * Create Date: 2018-11-23 * Modified By: jzh * Modified Date: 2018-11-23 * Why & What is modified: * Version: <1.0> */ public class SQLiteDBUtil { private static SQLiteDBUtil dbUtil; private SQLiteDatabase db; /** * 单例模式 * @return */ public static SQLiteDBUtil getInstance() { if (dbUtil == null) { dbUtil = new SQLiteDBUtil(); return dbUtil; } return dbUtil; } /** * 初始化/建表 * @param context 上下文对象 */ public void init(Context context) { String path = context.getCacheDir().getPath() + "/cts.db"; db = SQLiteDatabase.openOrCreateDatabase(path, null); String sql = " create table if not exists app_users " + "(user_id integer primary key autoincrement, " + " user_code text(50), user_name text(50) ) "; db.execSQL(sql); } /** * 新增 */ public long insert(String usercode, String username) { ContentValues cv = new ContentValues(); cv.put("user_code", usercode); cv.put("user_name", username); long flag = db.insert("app_users", null, cv); return flag; } /** * 修改 */ public int update(String usercode, String username) { ContentValues cv = new ContentValues(); cv.put("user_name", username); int flag = db.update("app_users", cv, "user_code = ?", new String[]{usercode}); return flag; } /** * 删除 */ public int delete(String usercode) { int flag = db.delete("app_users", "user_code = ?", new String[]{usercode}); return flag; } /** * 查询数据 */ public String select(String user_code) { String username = ""; Cursor cursor = db.query("app_users", null, "user_code = ?", new String[]{user_code}, null, null, null); while (cursor.moveToNext()) { int userid = cursor.getInt(cursor.getColumnIndex("user_id")); username = cursor.getString(cursor.getColumnIndex("user_name")); Log.e("sqlite", String.valueOf(userid) + " " + username); } if (cursor != null) { cursor.close(); } return username; } }
调用
// sqlite调用测试 SQLiteDBUtil db = SQLiteDBUtil.getInstance(); db.init(this); db.insert("9001", "蒋智昊1"); db.insert("9002", "蒋智昊2"); db.insert("9003", "蒋智昊3"); db.insert("9004", "蒋智昊4"); db.update("9004", "蒋智昊5"); db.delete("9003"); String username = db.select("9004");