继承 SQLiteOpenHelper 类
public class MyDatabaseHelper extends SQLiteOpenHelper { final String createTable = "create table mtb(" + "id integer primary key autoincrement," + "name varchar(20)," + "password varchar(20)" + ")"; final String[] insertData = { "insert into mtb(name,password) values('n001','p001')", "insert into mtb(name,password) values('n002','p002')", "insert into mtb(name,password) values('n003','p003')" }; //第一个使用数据库时候会调用 @Override public void onCreate(SQLiteDatabase db) { db.execSQL(createTable); for(String sql:insertData){db.execSQL(sql);} } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("oldVersion: "+oldVersion+"\n newVersion: "+newVersion); } //name 为数据库名字 用相对路径即可 。 如直接传入数据库名字 “mydb” public MyDatabaseHelper(Context context,String name,int version) { super(context, name, null,version); } }
使用这个工具类
MyDatabaseHelper dbHelp = new MyDatabaseHelper(this, "mydb", 1); SQLiteDatabase db = dbHelp.getReadableDatabase(); db.execSQL("insert into mtb(name,password) values('n004','p004')");