Create Android SQLite database

Android provides full support for SQLite databases.Any databases you create will be accessible by name to anyclass in the application, but not outside the application.

The recommended method to create a new SQLite database is to create a subclass ofSQLiteOpenHelper and override theonCreate() method, in which youcan execute a SQLite command to create tables in the database. 

For example:

public class MyDb extends SQLiteOpenHelper {

    public static final String DB_NAME = "student_score.db";//数据库名
    public static final String TABLE_NAME = "student_score";//表名
    public static final String NAME = "name";//表中第二列 学生姓名
    public static final String SCORE = "score";//表中第三列 学生成绩

    public MyDb(Context context) {
        super(context, DB_NAME, null, 1);// 1 为数据库的版本
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建表
        String sql = "create table " + TABLE_NAME + " (_id integer primary key autoincrement," +
                NAME + " text," +
                SCORE + " text" + ")";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {}
}

You can then get an instance of your SQLiteOpenHelperimplementation using the constructor you've defined. To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database andprovides methods for SQLite operations.

MyDb myDb = new MyDb(context);
SQLiteDatabase readableDatabase = myDb.getReadableDatabase();
Run the application, I found the database file in the databases directory inside application package.

Open the database file is as follows.



SQLite数据库使用SQL命令增删改查


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值