首先建立一個類 DatabaseHelper 繼承SQLiteOpenHelper幫助類,定義數據庫版本,數據庫名稱,建立表名。sql
private static final int DATABASE_VERSION = 1; //數據庫版本號 private static final String DATABASE_NAME = "Test"; //數據庫名稱 private static final String HR_B_DEPT = "HR_B_DEPT";//部門
初始化數據庫
public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); }
建立表ide
@Override public void onCreate(SQLiteDatabase db) { String sqldept = "create table HR_B_DEPT(INNERID String PRIMARY KEY ,DEPTCODE text,DEPTNAME text,PARENTID text)"; db.execSQL(sqldept); }
建立一個類 UseDatabase,this
public class UseDatabase { Context context; DatabaseHelper dbhelper; public SQLiteDatabase sqlitedatabase; public UseDatabase(Context context) { super(); this.context = context; } //打開數據庫鏈接 public void opendb(Context context) { dbhelper = new DatabaseHelper(context); sqlitedatabase = dbhelper.getWritableDatabase(); } //關閉數據庫鏈接 public void closedb(Context context) { if(sqlitedatabase.isOpen()) { sqlitedatabase.close(); } } //插入表數據 public void insert (String table_name,ContentValues values) { opendb(context); sqlitedatabase.insert(table_name, null, values); closedb(context); } //更新數據 public int updatatable(String table_name,ContentValues values,int ID) { opendb(context); return sqlitedatabase.update(table_name, values, " Type_ID = ? ", new String[]{String.valueOf(ID)}); } //刪除表數據 public void delete(String table_name) { opendb(context); try{ sqlitedatabase.delete(table_name, null, null); }catch(Exception e) { e.printStackTrace(); } finally{ closedb(context); } } }
在UseDatabase中添加一個方法,查表數據spa
//查找數據 public JSONArray DeptArray() { JSONArray Items = new JSONArray(); try{ opendb(context); String sql = "SELECT * FROM HR_B_DEPT"; Cursor c = sqlitedatabase.rawQuery(sql, null); if(c!=null) { while(c.moveToNext()) { JSONObject item = new JSONObject(); item.put("INNERID", c.getString(c.getColumnIndex("INNERID"))); item.put("DEPTCODE", c.getString(c.getColumnIndex("DEPTCODE"))); item.put("DEPTNAME", c.getString(c.getColumnIndex("DEPTNAME"))); Items.put(item); } c.close(); } }catch(Exception e) { e.printStackTrace(); } finally { closedb(context); } return Items; }
在Activity中使用code
UseDatabase usedatabase = new UseDatabase(context);JSONArray list = new JSONArray();list = usedatabase.DeptArray();