1、MyOpenHelper类
public class MyOpenHelper extends SQLiteOpenHelper{
public MyOpenHelper(Context context) {
super(context, "test.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//聊天的数据库
db.execSQL("create table math_message(_id integer primary key autoincrement, name char(10),msg char(20), path char(20),time char(20))");
System.out.println("数据库被创建了");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("数据库升级了");
}
}
2、插入数据
public void insertApi(String name, String path) {
//把要插入的数据全部封装至ContentValues对象
MyOpenHelper oh = new MyOpenHelper(context);
SQLiteDatabase db = oh.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);//name列值
values.put("path", path);//path列值
db.insert("head", null, values);//head表名
db.close();
}
或者
//person 表名 插入数据为"小志", 14000, "13888"
db.execSQL("insert into person (name, salary, phone)values(?, ?, ?)", new Object[]{"小志", 14000, "13888"});
3、查询表的所有数据
public void chaxun() {
//把数据库的数据查询出来
MyOpenHelper oh = new MyOpenHelper(this);
SQLiteDatabase db = oh.getWritableDatabase();
//head表名
Cursor cursor = db.query("head", null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String name = cursor.getString(1);
String path = cursor.getString(2);
LocalHead q = new LocalHead(_id, name, path);
Localhead.add(q);
}
}
或者
//从person表查询name和salary
Cursor cursor = db.rawQuery("select name, salary from person", null);
while(cursor.moveToNext()){
//通过列索引获取列的值
String name = cursor.getString(cursor.getColumnIndex("name"));
String salary = cursor.getString(1);
System.out.println(name + ";" + salary);
}
5、删除
//删除person 表中name为呵呵的行
db.execSQL("delete from person where name = ?", new Object[]{"呵呵"});
或者
//i为成功删除的行数 person为表名
int i = db.delete("person", "name = ? and _id = ?", new String[]{"哈哈", "3"});
6、更新数据
//在person 表中将name为哈哈更新phone为186666
db.execSQL("update person set phone = ? where name = ?", new Object[]{186666, "哈哈"});
或者
ContentValues values = new ContentValues();
values.put("salary", 26000);
int i = db.update("person", values, "name = ?", new String[]{"哈哈"});
7、LocalHead 类
public class LocalHead {
private String _id;
private String name;
private String path;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public LocalHead(String _id, String name, String path) {
super();
this._id = _id;
this.name = name;
this.path = path;
}
}