在android中使用python与sql接口

发布于 2024-09-25 08:23:49 字数 290 浏览 1 评论 0原文

我知道你可以在 android 中使用 python 和其他脚本语言。但我还没有看到天气是否可以在android中使用python作为sqlite的接口。这可能吗?这是我第一个需要 sqlite 的 Android 应用程序,并且使用 java api 的速度很慢。

如果这是不可能的,有人可以给我指点一个关于 android 中 sqlite 的好教程吗?我找到了很多,但它们都完全不同,我完全不知道哪一个是最好的方法。

很难想象 google 希望你如何使用 sqlite 数据库。看起来您需要大约 10 个不同的类来查询数据库。

I know you can use python and other scripting languages in android. But I haven't seen weather or not it was possible to use python as an interface to sqlite in android. Is this possible? This is the first android app where I've needed sqlite, and using the java api's is retarded.

If this isn't possible, can someone point me to a good tutorial on sqlite in android? I've found a bunch, but all of them are entirely different and I'm totally lost on which is the best way to do it.

It's just hard to picture how google expects you to use the sqlite database. It seems like you need like 10 different classes just to query a database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

零度° 2024-10-02 08:23:49

实际上你只需要 3 个类:

ContentProvider,如下所示:< a href="http://developer.android.com/guide/topics/providers/content-providers.html" rel="nofollow">http://developer.android.com/guide/topics/providers/content- providers.html

其次,您需要的是 SQLiteOpenHelper最后但并非最不重要的一个 光标

编辑:刚刚注意到它从代码片段中看不出来 db 变量是什么。它是 SQLiteOpenHelper 或更好的我的扩展(其中我只重写了 onCreate、onUpgrade 和构造函数。请参见下文 ^^

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;
}

这样

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);
}

更新 1 个结果,或者是否应该查询所有结果。

您就可以决定是否只返回或 如果 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); 

据我所知,这基本上是所有也是最优雅的方法。

Actually you just need 3 classes:

A ContentProvider, as found here: http://developer.android.com/guide/topics/providers/content-providers.html

Second you need is a SQLiteOpenHelper and last but not least a Cursor

Edit: Just noticed it's not obvious from the snippets what the db variable is. It's the SQLiteOpenHelper or better my extension of it (where I've only overridden the onCreate, onUpgrade and constructor. See below ^^

The ContentProvider is the one which will be communicating with the database and do the inserts, updates, deletes. The content provider will also allow other parts of your code (even other Apps, if you allow it) to access the data stored in the sqlite.

You can then override the insert/delete/query/update functions and add your functionality to it, for example perform different actions depending on the URI of the intent.

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;
}

The UriMatcher is defined as

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);
}

This way you can decide if only 1 result shall be returned or updated or if all should be queried or not.

The SQLiteOpenHelper will actually perform the insert and also take care of upgrades if the structure of your SQLite database changes, you can perform it there by overriding

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();
        }
    }
}

and then the easiest part of all: Perform a query:

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); 

That's basically all and the most elegant way to do it as far as I know.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文