sqlite需要用到SQLiteOpenHelper
首先新建一个类继承自SQLiteOpenHelper
重写它的而方法
在构造方法(此处类名为DbOpenHelper)中可以只留下context参数。
name和version可以提出来,写成静态,因为通常用的都是相同的
但如果有多个表时就就要把name放进去了
public DbOpenHelper(Context context) {
<span style="white-space:pre"> </span>super(context, name, null, version);
<span style="white-space:pre"> </span>// TODO Auto-generated constructor stub
<span style="white-space:pre"> </span>}
第三个(即factory改为null)
在oncreate里添加如下代码创建表String sql="create table person(id integer primary key autoincrement,name varchar(64),address varchar(64),sex varchar(8))";
arg0.execSQL(sql);
id为自增值
1.添加
String sql="insert into person(name,address,sex) values(?,?,?)";
<h2><span style="font-weight: normal;">Object[] params={"张三","北京","男"};
</span></h2><h2><span style="font-weight: normal;">DbOpenHelper helper;
</span></h2><h2><span style="font-weight: normal;">database=helper.getWritableDatabase();
<span style="white-space: pre;"> </span>database.execSQL(sql, params);</span></h2>
2.修改
String sql="update person set name = ?,address = ?,sex = ? where id =?";
Object[] params={"acely","nope","male",1};
DbOpenHelper helper;
database=helper.getWritableDatabase();
<span style="white-space:pre"> </span>database.execSQL(sql,params);
3.删除(此处以删除id为1为例)
String sql="delete from person1 where id =?";
<pre name="code" class="java" style="font-size: 18px;">DbOpenHelper helper;
Object[] params={1};
database=helper.getWritableDatabase();database.execSQL(sql,params);
4.查询单个或多个(以查询id为1的为例)
通常要用到map储存各个属性的值
Map<String, String>map=new HashMap<String, String>();
<span style="font-size:18px;">String sql="select * from person where id=?";
database=helper.getWritableDatabase();</span>
<span style="font-size:18px;">String[] selectionArgs={"1"};
Cursor cursor=database.rawQuery(sql, selectionArgs);
int colums=cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 0; i < colums; i++) {
String cols_name=cursor.getColumnName(i);
String cols_value=cursor.getString(cursor.getColumnIndex(cols_name));
if (cols_value==null) {
cols_value="";
}
map.put(cols_name, cols_value);
}</span>
map储存了id为1的各个属性
4.查询全部
通常要用到list和map结合
SQLiteDatabase database=null;
List<Map<String, String>>list=new ArrayList<Map<String,String>>();
try {
String sql="select * from person";
database=helper.getWritableDatabase();
Cursor cursor=database.rawQuery(sql, selectionArgs);
int colums=cursor.getColumnCount();
while (cursor.moveToNext()) {
Map<String, String>map=new HashMap<String, String>();
for (int i = 0; i < colums; i++) {
String cols_name=cursor.getColumnName(i);
String cols_value=cursor.getString(cursor.getColumnIndex(cols_name));
if (cols_value==null) {
cols_value="";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (database!=null) {
database.close();
}
}
list储存了每个人的属性