DatabaseOpenHelper.java:
package com.iaiai.activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private static final String DBNAME = "iaiai"; // 数据库名子
private static final int VERSION = 1; // 版本
public DatabaseOpenHelper(Context context) {
// 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表
db.execSQL("CREATE TABLE ADMIN (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME VARCHAR(50), PHONE VARCHAR(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级更新
db.execSQL("DROP TABLE IF EXISTS ADMIN");
onCreate(db);
}
}
IaiaiActivity.java类:
package com.iaiai.activity;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
public class IaiaiActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(this);
databaseOpenHelper.getWritableDatabase().execSQL(
"insert into ADMIN(name, phone) values (?, ?)",
new Object[] { "用户名1", "111111" });
Cursor cursor = databaseOpenHelper.getReadableDatabase().query("ADMIN",
new String[] { "count(*)" }, null, null, null, null, null);
if (cursor.moveToNext()) {
Log.i("******************SQL", "总记录数:" + cursor.getLong(0));
}
// cursor = databaseOpenHelper.getReadableDatabase().rawQuery("select ID,NAME,PHONE from ADMIN where id=?",
// new String[]{String.valueOf(1)});
cursor = databaseOpenHelper.getReadableDatabase().query("ADMIN",null, null, null, null, null, null);
while(cursor.moveToNext()){
int adminId = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
Log.i("******************数据"+adminId, "NAME:" + name+"----PHONE:"+phone);
}
}
}
只写了最简单的创建数据库,和添加查询数据,其它方法都很简单,这里不再写了。
运行结果: