android 创建本地数据库的具体代码
时间: 2023-12-13 14:05:44 浏览: 77
当您创建一个新的Java类来管理数据库时,可以按照以下示例代码编写:
```java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 如果需要升级数据库,可以在这里进行操作
// 例如,可以删除旧表并创建新表
String dropTableQuery = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(dropTableQuery);
onCreate(db);
}
}
```
在需要使用数据库的Activity中,可以使用以下代码来创建数据库实例并进行操作:
```java
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 插入数据示例
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, "John Doe");
long newRowId = db.insert(DBHelper.TABLE_NAME, null, values);
// 查询数据示例
String[] projection = {DBHelper.COLUMN_ID, DBHelper.COLUMN_NAME};
Cursor cursor = db.query(DBHelper.TABLE_NAME, projection, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_NAME));
// 处理查询到的数据
}
cursor.close();
db.close();
```
这样,您就可以在Android应用程序中创建本地数据库并进行操作。
阅读全文