public class Sql extends SQLiteOpenHelper {
public Sql(Context context) {
/**
* name 数据库的名字
* factory 工厂 默认的游标工厂 目的是创建 cursor
* version 数据库的版本 从1开始
*
*/
super(context, "user", null, 1);
}
/**
* 当数据库第一次创建的时候调用
*
* 特别适合做 表结构的初始化
*/
@Override
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists user (_id integer primary key autoincrement,name varchar(20),money varchar(20))");
//初始化2条数据
db.execSQL("insert into user ('name','money') values ('张三','2000')");
db.execSQL("insert into user ('name','money') values ('李四','5000')");
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists user (_id integer primary key autoincrement,name varchar(20),money varchar(20))");
//初始化2条数据
db.execSQL("insert into user ('name','money') values ('张三','2000')");
db.execSQL("insert into user ('name','money') values ('李四','5000')");
}
/**
* 当数据库版本需要升级的时候调用
*
* 适合做 表结构更新的操作
*
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade");
}
}
调用 Sql sql=new Sql(this);
SQLiteDatabase writableDatabase = sql.getWritableDatabase();
//Sqlite 为创建数据库类 Sqlite sql = new Sqlite(this); SQLiteDatabase writableDatabase = sql.getWritableDatabase(); //增加 ContentValues nullColumnHack = new ContentValues(); nullColumnHack.put("name", "李四"); nullColumnHack.put("age", "16"); writableDatabase.insert("user", null, nullColumnHack); //增加 ContentValues nullColumnHack2 = new ContentValues(); nullColumnHack2.put("name", "王五"); nullColumnHack2.put("age", "15"); writableDatabase.insert("user", null, nullColumnHack2); //删除 writableDatabase.delete("user", "name=?", new String[] { "李四" }); //修改 ContentValues values = new ContentValues(); values.put("name", "王五123");//修改后 writableDatabase.update("user", values, "name=?", new String[] { "王五" });//现在的名字 //查询所有 //id,name,age Cursor query = writableDatabase.query("user", null, null, null, null, null, null); String string = ""; list = new ArrayList<User>(); while (query.moveToNext()) { int id = query.getInt(0); String name = query.getString(1); String age = query.getString(2); // Toast.makeText(MainActivity.this, name+age, 0).show(); list.add(new User(name, age)); } ; // writableDatabase.execSQL("select *from user", null); TextView text = (TextView) findViewById(R.id.text); text.setText(list.toString());