1.创建SQLite引用变量
private SQLiteDatabase msg_db = null;
2.创建数据库
//创建数据库
private void creatDb(String dbNamePart){
msg_db = openOrCreateDatabase(dbNamePart, MODE_PRIVATE, null);
}
3.创建table和删除table
//创建table
private void creatTable(String tableNamePart){
String sql = "create table " + tableNamePart + " (name text, phone text, addr text, post text)";
Log.v("SQLiteDatabase", sql);
if(msg_db != null){
try{
msg_db.execSQL(sql);
}
catch(SQLException e){
Log.w("SQLiteDatabase",e.getMessage());
}
}
}
//删除表
@SuppressWarnings("unused")
private void deleteTable(String tableNamePart){
String sql = "drop table " + tableNamePart;
Log.v("SQLiteDatabase", sql);
try{
msg_db.execSQL(sql);
}
catch(SQLException e){
Log.w("SQLiteDatabase",e.getMessage());
}
}
4.添加、删除、更新table中的内容
//向表中添加内容
private void addRceord(String tableName, String name, String phone, String addr, String post) {
String sql = "insert into " + tableName + " values (" + "'" + name + "'" +"," + "'"+ phone + "'" +"," + "'"+ addr +"'" +"," + "'"+ post +"'" +")";
Log.v("SQLiteDatabase", sql);
if(msg_db != null){
try{
msg_db.execSQL(sql);
}
catch(SQLException e){
Log.w("SQLiteDatabase",e.getMessage());
}
}
}
//删除表中某一内容
@SuppressWarnings("unused")
private void delRceord(String tableNameString, String name) {
String sql = "delete from " + tableNameString + " where name = " + name;
Log.v("SQLiteDatabase", sql);
if(msg_db != null){
try{
msg_db.execSQL(sql);
}
catch(SQLException e){
Log.w("SQLiteDatabase",e.getMessage());
}
}
}
5.读取table中的内容
private void readRecord(String tableName){
String sql = "select * from " + tableName;
Log.v("SQLiteDatabase", sql);
Cursor cursor = null;
String str = "";
int nameIndex = 0;
int phoneIndex = 0;
int addrIndex = 0;
int postIndex = 0;
if(msg_db != null){
try{
cursor = msg_db.rawQuery(sql, null);
nameIndex = cursor.getColumnIndex("name");
phoneIndex = cursor.getColumnIndex("phone");
addrIndex = cursor.getColumnIndex("addr");
postIndex = cursor.getColumnIndex("post");
while(cursor.moveToNext()){
str = cursor.getString(nameIndex) + " " + cursor.getString(phoneIndex) + " "
+ cursor.getString(addrIndex) + " " + cursor.getString(postIndex);
Log.v("SQLiteDatabase", str);
}
cursor.close();
}
catch(SQLException e){
Log.w("SQLiteDatabase",e.getMessage());
}
}
}
阅读(1540) | 评论(0) | 转发(0) |