要解决Android应用程序无法正确读取SQLite数据库中的第三个整数列的问题,可以使用以下代码示例:
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表格
String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, score INTEGER);";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级数据库
String dropTableQuery = "DROP TABLE IF EXISTS mytable;";
db.execSQL(dropTableQuery);
onCreate(db);
}
}
public class MainActivity extends AppCompatActivity {
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// 写入数据
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 25);
values.put("score", 85);
db.insert("mytable", null, values);
// 读取数据
db = dbHelper.getReadableDatabase();
String[] projection = {"name", "age", "score"};
Cursor cursor = db.query("mytable", projection, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
// 读取字符串列
String name = cursor.getString(cursor.getColumnIndex("name"));
// 读取第三个整数列
int score = cursor.getInt(cursor.getColumnIndex("score"));
Log.d("MainActivity", "Name: " + name + ", Score: " + score);
} while (cursor.moveToNext());
}
cursor.close();
}
@Override
protected void onDestroy() {
super.onDestroy();
dbHelper.close();
}
}
通过以上代码示例,你可以正确读取字符串列和第三个整数列的数据。确保在读取整数列时使用getInt
方法,并正确指定整数列的索引。