How do you write code to create a database in Android?
The code to create a database on Android is as follows:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据库表的SQL语句
String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)";
// 执行创建表的SQL语句
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 在数据库版本更新时执行的操作
// 可以在此处添加删除表、添加新表等操作
}
}
The code above defines a class called DatabaseHelper that inherits from SQLiteOpenHelper. In the constructor of DatabaseHelper, we specify the name and version number of the database.
The onCreate() method is used to create database tables, where we can execute SQL statements to create the tables. In the example above, a table named mytable is created with two columns: id and name.
The onUpgrade() method is called when the database version is updated, and we can perform update operations in this method, such as adding new tables or deleting tables.
Next, in your application, instantiate the DatabaseHelper class and call the getWritableDatabase() method to obtain a writable database object. The sample code is as follows:
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Now that you have successfully created a database, you can use the db object to execute SQL statements for database operations.