创建WFDBHelper类,该类继承于SQLiteOpenHelper类,改写onCreate方法。
package com.liu_weifeng.wf;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class WFDBHelper extends SQLiteOpenHelper {
public WFDBHelper(Context context){
super(context,"WF.db",null,2);
}
//数据库第一次创建时调用该方法
public void onCreate(SQLiteDatabase db){
//创建用户信息表userInformation,该表包含每个用户的基本信息
db.execSQL("CREATE TABLE userInformation (Account VARCHAR(11) PRIMARY KEY,Password VARCHAR(10),Nickname VARCHAR(15),Sex VARCHAR(2),Signature VARCHAR(50),Head VARCHAR(10))");
//userInformation添加记录
db.execSQL("INSERT INTO userInformation(Account,Password,Nickname,Sex,Signature,Head) VALUES (?,?,?,?,?,?)",
new Object[]{"1875","123456_","刘","男","Hello,World!","head_1");
}
//当数据库的版本号增加时调用
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
}
}
对数据库的简单操作
对表的查询:
WFDBHelper helper=new WFDBHelper(this);
db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM userInformation WHERE Account=?", new String[]{"1875"});
cursor.moveToFirst();
//读取性别
String sex=cursor.getString(3); //从0计,第三列为Sex
String sex1=cursor.getString(cursor.getColumnIndex("Sex")); //或使用getColumnIndex()方法
/*
cursor.getColumnIndex("Sex"); //获取Sex列为第几列
cursor.getColumnCount(); //获取cursor中的总列数
cursor.getColumnName(i); //获取cursor中第i列的列名
cursor.isNull(i); //判断第i列是否为空
cursor.getCount(); //获取cursor中的总行数
*/
cursor.close();
db.close();
对表的增,删,改:
WFDBHelper helper=new WFDBHelper(this);
SQLiteDatabase db=helper.getWriteableDaatabase();
//增加一条记录
db.execSQL("INSERT INTO userInformation (Account,Password,Nickname,Sex,Signature,Head) VALUES (?,?,?,?,?,?)",
new Object[]{"1876","123456_","刘","男","Hello,World!","head_2"});
//在userInformation表的结尾增加名为Message的列
db.execSQL("ALTER TABLE userInformation ADD Message VARCHAR(11)");
//修改一条记录
db.execSQL("UPDATE userInformation SET Nickname=? WHERE Account=?", new String[]{nickname, currentUserAccount});
//删除一条记录
db.execSQL("DELETE FROM userInformation WHERE Account=1875");
db.close();