一、SQLite数据库的创建
创建一个名 UserManager.db 的数据库,然后在这个数据库中创建一张 Users 表,用来存放用户信息。
代码如下:
class MyDataBaseHelper extends SQLiteOpenHelper {
public static final String CREATE_USERS= "create table users ("
+ "id integer primary key autoincrement, "
+ "username text, "
+ "password text, "
+ "age integer)";
private Context mContext;
public MyDatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version){
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USERS);
Toast.makeText(mContext, "数据库创建成功!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
}
接下来需要创建 MyDataBaseHelper 对象,调用
对象的 getReadableDatabase()或 getWritableDatabase()方法,才能成功创建数据库。
public class MainActivity extends AppCompatActivity {
private MyDataBaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new MyDataBaseHelper(this,"UserManager.db"