无法使用游标查询SQLite数据库

时间:2017-08-22 06:58:57

标签: java android sqlite android-sqlite

我对Android中的SQLite很新,我需要帮助。 我创建了一个Android项目,我想使用内容提供程序访问do数据库。这是我的代码

清单文件中的提供程序

<provider android:name="NaTempsProvider"
    android:authorities="com.sdnsoft.natemps.natemps.data.NaTempsProvider.provider"
    android:exported="false"
    android:enabled="true">
    <grant-uri-permission android:pathPattern=".*" />
</provider>

合同

public class NaTempsContract {
public static final String AUTHORITY = "com.sdnsoft.natemps.natemps.data.NaTempsProvider.provider";// This class cannot be instantiated
private NaTempsContract() {
}

public static final class app_role implements BaseColumns {

    // This class cannot be instantiated
    private app_role() {
    }

    /**
     * The table name offered by this provider
     */
    public static final String TABLE_NAME = "app_role";

    /*
     * URI definitions
     */

    /**
     * The scheme part for this provider's URI
     */
    private static final String SCHEME = "content://";


    /**
     * Path part for the app_role URI
     */
    private static final String PATH_APP_ROLE = "/app_role";

    /**
     * Path part for the app_role ID URI
     */
    private static final String PATH_APP_ROLE_ID = "/app_role/";

    /**
     * The content:// style URL for this table
     */
    public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_APP_ROLE);


    /**
     * The default sort order for this table
     */
    public static final String DEFAULT_SORT_ORDER = "name DESC";


    /*
     * Column definitions
     */

    /**
     * <P>Type: INTEGER</P>
     */
    public static final String COLUMN_NAME_ID = "id";

    /**
     * <P>Type: TEXT</P>
     */
    public static final String COLUMN_NAME_NAME = "name";

    /**
     * <P>Type: TEXT</P>
     */
    public static final String COLUMN_NAME_DISPLAY_NAME = "display_name";

}}

提供者

public class NaTempsProvider
    extends ContentProvider implements ContentProvider.PipeDataWriter<Cursor> {    // Used for debugging and loggingprivate static final String TAG = "NaTempsProvider";

private static final int DATABASE_VERSION = 1;


// Handle to a new DatabaseHelper.
private DatabaseHelper mOpenHelper;

static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {

        // calls the super constructor, requesting the default cursor factory.
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }    // all type into database

    public static final String PRIMARY_KEY_TYPE = " INTEGER PRIMARY KEY AUTOINCREMENT ";
    // Structure de la table `app_role`

    public static final String APP_ROLE_TABLE_NAME = "app_role";
    public static final String APP_ROLE_PRIMARY_KEY = "id";

    public static final String APP_ROLE_NAME = "name";
    public static final String APP_ROLE_DISPLAY_NAME = "display_name";
    public static final String APP_ROLE_CREATE =
            "CREATE TABLE " + APP_ROLE_TABLE_NAME + " (" +
                    APP_ROLE_PRIMARY_KEY + PRIMARY_KEY_TYPE + "," +
                    APP_ROLE_NAME + " TEXT," +
                    APP_ROLE_DISPLAY_NAME +
                    " TEXT);INSERT INTO `app_role` (`id`, `name`, `display_name`) VALUES\n" +
                    "(1, 'accueil', 'Accueil'),\n" +
                    "(2, 'responsable_cercle', 'responsable de cercle');\n";


    public static final String APP_ROLE_TABLE_DROP = "DROP TABLE IF EXISTS " + APP_ROLE_TABLE_NAME + ";";

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                APP_ROLE_CREATE
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(
                APP_ROLE_TABLE_DROP
        );
        onCreate(db);
    }

}

@Override
public boolean onCreate() {

    // Creates a new helper object. Note that the database itself isn't opened until
    // something tries to access it, and it's only created if it doesn't already exist.
    mOpenHelper = new DatabaseHelper(getContext());

    // Assumes that any failures will be reported by a thrown exception.
    return true;
}
...}

在我的活动中:创建

// If there is no data associated with the Intent, sets the data to the default URI, which
    // accesses a list of notes.
    if (intent.getData() == null) {
        intent.setData(NaTempsContract.app_role.CONTENT_URI);
    }

    /* Performs a managed query. The Activity handles closing and requerying the cursor
     * when needed.
     *
     * Please see the introductory note about performing provider operations on the UI thread.
     */
    Cursor cursor = managedQuery(
            getIntent().getData(),            // Use the default content URI for the provider.
            NaTempsProjections.APP_ROLE_PROJECTION,                       // Return the note ID and title for each note.
            null,                             // No where clause, return all records.
            null,                             // No where clause, therefore no where column values.
            null  // Use the default sort order.
    );

但是当我运行project时,游标为null。并且无法使用数据

3 个答案:

答案 0 :(得分:0)

光标不是 null ,只是为空。这有很大的不同 SQLite不允许在同一行上有多个命令。

这就是分号(;)完全没用的原因 INSERT之后的CREATE TABLE命令只是被忽略

在2个单独的SQL命令字符串上使用2个单独的execSQL()指令。

答案 1 :(得分:0)

根据您的代码,Table已成功创建,只有插入问题。使用如下代码插入数据

UIActivityViewController *vc = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];

vc.excludedActivityTypes = @[UIActivityTypeMessage];
vc.popoverPresentationController.barButtonItem = self.shareButton;
    vc.popoverPresentationController.permittedArrowDirections = 
UIPopoverArrowDirectionAny;
    vc.popoverPresentationController.delegate = self;
    vc.modalPresentationStyle = UIModalPresentationPopover;

答案 2 :(得分:0)

问题可能与execSQL方法只能处理单个SQL语句这一事实有关。因此,您需要拆分两个SQL语句(表创建和数据插入),然后使用execSQL方法两次,例如。

public static final String APP_ROLE_CREATE =
            "CREATE TABLE " + APP_ROLE_TABLE_NAME + " (" +
                    APP_ROLE_PRIMARY_KEY + PRIMARY_KEY_TYPE + "," +
                    APP_ROLE_NAME + " TEXT," +
                    APP_ROLE_DISPLAY_NAME +
                    " TEXT);";

public static final String APP_ROLE_INSERT = "INSERT INTO `app_role` (`id`, `name`, `display_name`) VALUES\n" +
                    "(1, 'accueil', 'Accueil'),\n" +
                    "(2, 'responsable_cercle', 'responsable de cercle');\n";

@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                APP_ROLE_CREATE
        );
        db.execSQL(
                APP_ROLE_INSERT
        );
    }

使用以下内容进行测试: -

Cursor csr = dbhlpr.getWritableDatabase().query(DatabaseHelper.APP_ROLE_TABLE_NAME,null,null,null,null,null,null);
        String logdata;
        while (csr.moveToNext()) {
            logdata = "Data in Row=" + csr.getPosition();
            for (int i=0; i < csr.getColumnCount(); i++) {
                logdata = logdata +
                        "\n\t" + "Column Name=" + csr.getColumnName(i) +
                        " Value=" + csr.getString(i);
            }
            Log.d("ROWINFO",logdata);
        }
        csr.close();

导致: -

08-22 17:32:03.332 4103-4103/mjt.so45787986 D/ROWINFO: Data in Row=0
                                                        Column Name=id Value=1
                                                        Column Name=name Value=accueil
                                                        Column Name=display_name Value=Accueil
08-22 17:32:03.332 4103-4103/mjt.so45787986 D/ROWINFO: Data in Row=1
                                                        Column Name=id Value=2
                                                        Column Name=name Value=responsable_cercle
                                                        Column Name=display_name Value=responsable de cercle

我建议您可能需要卸载App,删除应用程序的数据或增加版本号,因为该表可能已经创建。

或者你可以自己运行两个中的第二个,即(db.execSQL(APP_ROLE_INSERT);)。但是,您可能需要考虑最终应用程序的代码应该是什么。