cursor.MySQLCursorDict Class

5.9.6.4 cursor.MySQLCursorDict Class

The MySQLCursorDict class inherits from MySQLCursor. This class is available as of Connector/Python 2.0.0.

MySQLCursorDict cursor returns each row as a dictionary. The keys for each dictionary object are the column names of the MySQL result.

Example:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")
print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']

The preceding code produces output like this:

Countries in Europe:
* Albania
* Andorra
* Austria
* Belgium
* Bulgaria
...

It may be convenient to pass the dictionary to format() as follows:

cursor.execute("SELECT Name, Population FROM country WHERE Continent = 'Europe'")
print("Countries in Europe with population:")
for row in cursor:
    print("* {Name}: {Population}".format(**row))
 PREV    HOME    UP    NEXT 
 User Comments
   Posted by blair gemmer on December 15, 2014
If you want to use stored procedures, please use this format:

cursor.callproc(stored_procedure_name, args)
result = []
for recordset in cursor.stored_results():
for row in recordset:
result.append(dict(zip(recordset.column_names,row)))
 
==============
 

10.5.11 MySQLCursor.column_names Property

Syntax:

sequence = cursor.column_names

This read-only property returns the column names of a result set as sequence of Unicode strings.

The following example shows how to create a dictionary from a tuple containing data with keys using column_names:

cursor.execute("SELECT last_name, first_name, hire_date "
               "FROM employees WHERE emp_no = %s", (123,))
row = dict(zip(cursor.column_names, cursor.fetchone()))
print("{last_name}, {first_name}: {hire_date}".format(row))

Alternatively, as of Connector/Python 2.0.0, you can fetch rows as dictionaries directly; see Section 10.6.4, “cursor.MySQLCursorDict Class”.

转载于:https://www.cnblogs.com/kungfupanda/p/5937342.html

<think>嗯,用户想知道如何通过Cursor对象从Android数据库中提取数据。首先,我需要回忆一下Android中数据库操作的基本流程。记得ContentResolver的query方法会返回Cursor,然后通过Cursor的方法来获取数据。 首先,用户可能需要知道如何遍历Cursor。比如,使用moveToFirst()和moveToNext()来逐行处理数据。然后,对于每一行,如何根据列名获取对应的值。例如,用getColumnIndex()获取列索引,再用getInt、getString等方法获取具体数据。 用户还提到了DatabaseHelper示例,可能需要一个完整的代码例子,包括查询和使用Cursor的过程。比如,在DatabaseHelper中使用SQLiteDatabase的query方法,返回Cursor,然后在Activity中处理它。 另外,要注意异常处理和关闭Cursor,防止内存泄漏。应该提醒用户在使用完毕后调用close()方法,或者使用try-with-resources(但Android API level可能限制这个,所以可能需要传统的finally块)。 用户可能还关心数据类型转换,比如如何获取不同类型的数据,比如整型、字符串或者日期。需要说明不同的get方法对应不同的数据类型。 还有,是否需要处理空指针的情况?比如,确保Cursor不为null,并且moveToFirst()返回true,表示有数据存在。否则,直接操作可能导致崩溃。 可能还需要提到使用Loader或者CursorLoader来异步加载数据,避免在主线程中操作数据库导致ANR。但用户的问题可能更基础,先给出基本示例,再提到优化方法。 现在组织一下步骤:首先获取Cursor,检查是否有数据,循环遍历每一行,按列名取出数据。代码示例应该包括这些步骤,并处理可能的异常。 此外,引用中的内容提到ContentResolver的query方法返回Cursor,可以参考引用[2]和[3]。例如,在引用[3]中提到使用query()方法返回Cursor,并遍历获取结果,这可能需要引用到回答中。 最后,确保代码示例正确,使用DatabaseHelper类,展示如何执行查询并处理Cursor。可能还需要解释代码中的关键部分,比如列名的使用,关闭Cursor的重要性。</think>在Android中通过Cursor对象提取数据的步骤如下,结合DatabaseHelper示例代码说明: ### 1. 基础数据提取流程 ```java // 获取Cursor对象(通过ContentResolver或SQLiteDatabase) Cursor cursor = db.query( "user_table", new String[]{"_id", "name", "age"}, null, null, null, null, null ); // 检查数据有效性 if (cursor != null && cursor.moveToFirst()) { do { // 通过列名获取索引 int idIndex = cursor.getColumnIndex("_id"); int nameIndex = cursor.getColumnIndex("name"); int ageIndex = cursor.getColumnIndex("age"); // 提取数据(需处理可能返回-1的情况) if(idIndex != -1) { int id = cursor.getInt(idIndex); String name = cursor.getString(nameIndex); int age = cursor.getInt(ageIndex); // 使用数据... Log.d("DB", "ID:" + id + " Name:" + name + " Age:" + age); } } while (cursor.moveToNext()); // 关闭Cursor[^3] cursor.close(); } ``` ### 2. 完整DatabaseHelper示例 ```java public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "user_db"; private static final int DB_VERSION = 1; public MyDatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE user_table (_id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"); } // 查询方法示例 public Cursor getAllUsers() { SQLiteDatabase db = this.getReadableDatabase(); return db.query( "user_table", new String[]{"_id", "name", "age"}, null, null, null, null, null ); } } // 在Activity中使用 MyDatabaseHelper dbHelper = new MyDatabaseHelper(this); Cursor cursor = dbHelper.getAllUsers(); // 处理Cursor数据(同上) ``` ### 关键点说明: 1. **列索引获取**:建议使用`cursor.getColumnIndexOrThrow()`代替`getColumnIndex()`避免空指针[^3] 2. **数据类型转换**: - 整型:`getInt()` - 字符串:`getString()` - 浮点:`getDouble()` - BLOB:`getBlob()` 3. **空值处理**:使用`isNull(columnIndex)`检查字段是否为空 4. **性能优化**:使用`try-with-resources`自动关闭(需要API 19+): ```java try (Cursor cursor = db.query(...)) { // 数据处理 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值