在安卓中使用Python接口连接SQL

0 投票
1 回答
4278 浏览
提问于 2025-04-16 04:37

我知道在安卓上可以使用Python和其他脚本语言。但是我还没有看到是否可以用Python作为安卓中SQLite的接口。这可能吗?这是我第一次在安卓应用中需要用到SQLite,而使用Java的API让我觉得很麻烦。

如果这不行,有人能推荐一个关于安卓中SQLite的好教程吗?我找到了一堆,但每个都完全不同,我完全搞不清楚哪个是最好的方法。

我真的很难想象谷歌希望你怎么使用SQLite数据库。感觉你需要大约10个不同的类才能查询一个数据库。

1 个回答

1

其实你只需要三个类:

第一个是 ContentProvider,你可以在这里找到相关信息:http://developer.android.com/guide/topics/providers/content-providers.html

第二个是 SQLiteOpenHelper,最后一个是 Cursor

补充:我刚注意到代码片段中并没有明确说明 db 变量是什么。它是 SQLiteOpenHelper,或者更准确地说是我对它的扩展(我只重写了 onCreate、onUpgrade 和构造函数。见下面的内容 ^^

ContentProvider 是用来和数据库沟通的,它负责插入、更新和删除数据。ContentProvider 还可以让你代码的其他部分(甚至是其他应用,如果你允许的话)访问存储在 SQLite 中的数据。

你可以重写插入、删除、查询和更新的功能,添加你自己的功能,比如根据意图的 URI 执行不同的操作。

public int delete(Uri uri, String whereClause, String[] whereArgs) {
    int count = 0;

    switch(URI_MATCHER.match(uri)){
    case ITEMS:
        // uri = content://com.yourname.yourapp.Items/item
        // delete all rows
        count = db.delete(TABLE_ITEMS, whereClause, whereArgs);
        break;
    case ITEMS_ID:
        // uri = content://com.yourname.yourapp.Items/item/2
        // delete the row with the id 2
        String segment = uri.getPathSegments().get(1);
        count = db.delete(TABLE_ITEMS, 
                Item.KEY_ITEM_ID +"="+segment
                +(!TextUtils.isEmpty(whereClause)?" AND ("+whereClause+")":""),
                whereArgs);
        break;
    default:
        throw new IllegalArgumentException("Unknown Uri: "+uri);
    }

    return count;
}

UriMatcher 的定义是

private static final int ITEMS = 1;
private static final int ITEMS_ID = 2;
private static final String AUTHORITY_ITEMS ="com.yourname.yourapp.Items";
private static final UriMatcher URI_MATCHER;

static {
    URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    URI_MATCHER.addURI(AUTHORITY_ITEMS, "item", ITEMS);
    URI_MATCHER.addURI(AUTHORITY_ITEMS, "item/#", ITEMS_ID);
}

这样你就可以决定是只返回或更新一个结果,还是查询所有结果。

SQLiteOpenHelper 实际上会执行插入操作,并在你的 SQLite 数据库结构发生变化时处理升级,你可以通过重写

class ItemDatabaseHelper extends SQLiteOpenHelper {
    public ItemDatabaseHelper(Context context){
        super(context, "myDatabase.db", null, ITEMDATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String createItemsTable = "create table " + TABLE_ITEMS + " (" +
            ...
        ");";

        // Begin Transaction
        db.beginTransaction();
        try{
            // Create Items table
            db.execSQL(createItemsTable);

            // Transaction was successful
            db.setTransactionSuccessful();
        } catch(Exception ex) {
            Log.e(this.getClass().getName(), ex.getMessage(), ex);
        } finally {
            // End transaction
            db.endTransaction();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String dropItemsTable = "DROP TABLE IF EXISTS " + TABLE_ITEMS;

        // Begin transaction
        db.beginTransaction();

        try {
            if(oldVersion<2){
                // Upgrade from version 1 to version 2: DROP the whole table
                db.execSQL(dropItemsTable);
                onCreate(db);
                Log.i(this.getClass().toString(),"Successfully upgraded to Version 2");
            }
            if(oldVersion<3) {
                // minor change, perform an ALTER query
                db.execSQL("ALTER ...");
            }

            db.setTransactionSuccessful();
        } catch(Exception ex){
            Log.e(this.getClass().getName(), ex.getMessage(), ex);
        } finally {
            // Ends transaction
            // If there was an error, the database won't be altered
            db.endTransaction();
        }
    }
}

然后是最简单的部分:执行查询:

String[] rows = new String[] {"_ID", "_name", "_email" };
Uri uri = Uri.parse("content://com.yourname.yourapp.Items/item/2";

// Alternatively you can also use getContentResolver().insert/update/query/delete methods
Cursor c = managedQuery(uri, rows, "someRow=1", null, null); 

基本上这就是所有内容,按照我所知道的,这是最优雅的做法。

撰写回答