android studio从数据库读取数据
时间: 2023-09-10 09:06:17 浏览: 133
可以通过 SQLiteOpenHelper 类来连接数据库并打开一个读取器(ReadableDatabase),然后使用 Cursor 对象进行查询操作,最后关闭读取器。具体实现可以参考以下代码:
首先定义一个数据库帮助类 DatabaseHelper,继承自 SQLiteOpenHelper:
```
public class DatabaseHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "my_database.db";
// 数据库版本号
private static final int DB_VERSION = 1;
// 数据表名称
public static final String TABLE_NAME = "my_table";
// 列名称
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AGE = "age";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据表
String sql = "CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_AGE + " INTEGER)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库升级时执行的操作
}
}
```
然后在 MainActivity 中读取数据:
```
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建或打开数据库
DatabaseHelper dbHelper = new DatabaseHelper(this);
db = dbHelper.getReadableDatabase();
// 查询数据
String[] projection = {
DatabaseHelper.COLUMN_ID,
DatabaseHelper.COLUMN_NAME,
DatabaseHelper.COLUMN_AGE
};
Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, projection, null, null, null, null, null);
// 遍历数据
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_AGE));
Log.d("MainActivity", "id = " + id + ", name = " + name + ", age = " + age);
} while (cursor.moveToNext());
}
// 关闭资源
cursor.close();
db.close();
}
}
```
注意要在 AndroidManifest.xml 中申请访问 SQLite 数据库的权限:
```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
```
阅读全文