这是一个使用Android和SQLite进行查询的代码示例:
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) {
// 创建表格和定义结构
String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级数据库的方法
}
public List getAllNames() {
List names = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT name FROM mytable", null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
names.add(name);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return names;
}
}
public class MainActivity extends AppCompatActivity {
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(this);
List names = databaseHelper.getAllNames();
// 打印查询结果
for (String name : names) {
Log.d("TAG", "Name: " + name);
}
}
}
这个示例展示了如何使用Android和SQLite进行查询操作。你可以根据自己的需求修改表格结构和查询语句。请确保在使用数据库时遵循最佳实践,例如关闭数据库连接和使用参数化查询来防止SQL注入攻击。