SqlLite
public class DBHelper {
public static final String DB_DBNAME = "scanner";//数据库名称
public static final String DB_TABLENAME = "product";//数据表名称
public static final int VERSION = 4;//版本 更新的时候有用,一般无用
public static SQLiteDatabase dbInstance;
private MyDBHelper myDBHelper;//帮助类,创建表字段
private StringBuffer tableCreate;
private Context context;
public DBHelper(Context context)
{
this.context = context;
}
public void openDatabase() {
//创建数据库
if (dbInstance == null) {
myDBHelper = new MyDBHelper(context, DB_DBNAME, VERSION);
dbInstance = myDBHelper.getWritableDatabase();
}
}
/**
* 往数据库里面的product表插入一条数据,若失败返回-1
*
* @param user
* @return 失败返回-1
*/
public long insert(Model model) {
ContentValues values = new ContentValues();
values.put("productName", model.productName);
values.put("productType", model.productType);
return dbInstance.insert(DB_TABLENAME, null, values);
}
/**
* 修改数据库中的一条记录
*
* @param user
*/
public void modify(Model model) {
ContentValues values = new ContentValues();
values.put("productName", model.productName);
values.put("productType", model.productType);
dbInstance.update(DB_TABLENAME, values, "_id=?",
new String[] { String.valueOf(model._id) });
}
/**
* 删除数据库中的一条记录
*
* @param user
*/
public void delete(int _id) {
dbInstance.delete(DB_TABLENAME, "_id=?",
new String[] { String.valueOf(_id) });
}
/**
* 获得数据库中所有的用户,将每一个用户放到一个map中去,然后再将map放到list里面去返回
*
* @return list
*/
public ArrayList<HashMap<String, Object>> getAllUser() {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
Cursor cursor = null;
cursor = dbInstance.query(DB_TABLENAME, new String[] { "_id",
"productName", "productType" }, null, null, null,
null, null);
while (cursor.moveToNext()) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
item.put("productName", cursor.getString(cursor.getColumnIndex("productName")));
item.put("productType",
cursor.getString(cursor.getColumnIndex("productType")));
list.add(item);
}
return list;
}
class MyDBHelper extends SQLiteOpenHelper {
public MyDBHelper(Context context, String name, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//create table
tableCreate = new StringBuffer();
tableCreate.append("create table ").append(DB_TABLENAME)
.append(" (")
.append("_id integer primary key autoincrement,")
.append("productName text,").append("productType text")
.append(")");
System.out.println(tableCreate.toString());
db.execSQL(tableCreate.toString());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table if exists " + DB_TABLENAME;
db.execSQL(sql);
myDBHelper.onCreate(db);
}
}
}
Android开发三:数据库设计及应用(一)
最新推荐文章于 2021-07-15 15:23:01 发布