Android SQLITE 操作工具类

时间:2020-12-19 13:27:31

首先创建一个类 DatabaseHelper 继承SQLiteOpenHelper帮助类,定义数据库版本,数据库名称,创建表名。

    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);
}

创建表

@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,

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中添加一个方法,查表数据

    //查找数据
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中使用

UseDatabase usedatabase = new UseDatabase(context);
JSONArray list = new JSONArray();
list = usedatabase.DeptArray();