Android中使用SQLite数据库要通过SQLiteOpenHelper类。
首先,定义相关变量:
class="brush:java;gutter:true;"> // 数据库变量 DatabaseHelper mDBH; SQLiteDatabase db; public static String strSql;
再定义SQLiteOpenHelper类:
public static class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "Call_db.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "Call";
public static final String TABLE_NAME_2 = "Days";
public static final String NAME = "Name";
public static final String NUMBER = "Number";
public static final String DATE = "Date";
public static final String DATES = "Dates";
public static final String YEAR = "Year";
public static final String MONTH = "Month";
public static final String DAY = "Day";
public static final String HOUR = "Hour";
public static final String MINUTE = "Minute";
public static final String DOW = "Dow";
public static final String TYPE = "Type";
public static final String INC = "InC";
public static final String OUTC = "OutC";
public static final String TOTAL = "Total";
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// 没有数据库时,建立数据库
@Override
public void onCreate(SQLiteDatabase db) {
strSql = "CREATE TABLE " + TABLE_NAME + " (" + NAME
+ " text not null, " + NUMBER + " text not null, " + DATE
+ " text not null, " + DATES
+ " text not null, "+ YEAR + " text not null, "
+ MONTH + " text not null, " + DAY + " text not null, "
+ HOUR + " text not null, " + MINUTE + " text not null, "
+ DOW + " text not null, " + TYPE + " text not null" + ");";
db.execSQL(strSql);
strSql = "CREATE TABLE " + TABLE_NAME_2 + " (" + DATES
+ " text not null, " + YEAR + " text not null, " + MONTH
+ " text not null, " + DAY
+ " text not null, "+ DOW + " text not null, "
+ INC + " text not null, " + OUTC + " text not null, "
+ TOTAL + " text not null);";
db.execSQL(strSql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
当数据库不存在时(如第一次运行时),调用onCreate(SQLiteDatabase db)建立数据库,建立的方法是定义SQL语句,再执行该语句。