在android中使用python来连接到sql

时间:2010-09-27 03:32:52

标签: android python sqlite android-scripting

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

如果这是不可能的,有人可以指点我在android中的sqlite上的一个很好的教程吗?我找到了一堆,但所有这些都完全不同,我完全迷失了,这是最好的方法。

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

1 个答案:

答案 0 :(得分:1)

实际上你只需要3个课程:

ContentProvider,如下所示:http://developer.android.com/guide/topics/providers/content-providers.html

第二,你需要的是SQLiteOpenHelper,最后但并非最不重要的是Cursor

编辑:刚刚注意到片段中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;
}

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

通过这种方式,您可以决定是否只返回或更新1个结果,或者是否应该查询所有结果。

如果SQLite数据库的结构发生变化,SQLiteOpenHelper将实际执行插入并处理升级,您可以通过覆盖来执行它

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

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