android studio SQLite获取数据
时间: 2023-09-11 11:11:28 浏览: 89
要从SQLite数据库中获取数据,需要执行以下步骤:
1. 创建SQLiteOpenHelper类,该类将帮助我们打开和创建数据库。
```java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydb.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) {
// 创建表格
db.execSQL("CREATE TABLE users (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 更新表格
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
```
2. 创建数据模型类,该类将表示表格中的一行。
```java
public class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
3. 创建数据访问类,该类将提供从数据库中获取数据的方法。
```java
public class UserDAO {
private SQLiteDatabase db;
public UserDAO(Context context) {
db = new DatabaseHelper(context).getWritableDatabase();
}
public List<User> getUsers() {
List<User> users = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
users.add(new User(id, name, age));
} while (cursor.moveToNext());
}
cursor.close();
return users;
}
}
```
4. 在Activity中使用数据访问类获取数据。
```java
public class MainActivity extends AppCompatActivity {
private UserDAO userDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userDAO = new UserDAO(this);
List<User> users = userDAO.getUsers();
// 使用获取到的数据
}
}
```
这样就可以从SQLite数据库中获取数据了。
阅读全文