【问题标题】:How to check whether a table exist in android sqlite [duplicate]如何检查android sqlite中是否存在表[重复]
【发布时间】:2016-06-15 12:06:29
【问题描述】:

我已经使用 sqlite 插入数据并取回结果,但我所做的是首先显示包含获取值的列表,如果没有值,然后列表显示指示用户添加新的空视图项目到 sqlite 数据库。 但是当我尝试这个时,它告诉我一个错误,数据库中不存在这样的表。 我想知道如何检查表是否已创建或是否有值。如果不是如何向用户抛出异常以向表中插入新项目。

数据库:

public class BuisnessDatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "receiptExample";

// Labels table name
private static final String TABLE_LABELS = "buisnesslabels";
private static final String KEY_ID = "id";
private static final String KEY_IMAGE = "image";
private static final String KEY_STATUS="status";
private static final String KEY_UPLOADSTATUS = "uplaodstatus";
private static final String KEY_USERID="userid";
SQLiteDatabase db;
public BuisnessDatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    // Category table create query
    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_IMAGE + " BLOB,"
            + KEY_STATUS + " TEXT,"
            + KEY_UPLOADSTATUS + " TEXT,"
            + KEY_USERID + " TEXT" + ");";

    db.execSQL(CREATE_CATEGORIES_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

    // Create tables again
    onCreate(db);
}
public void insertLabel(byte[] imag,String status,String uploadstatus,String userid){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    //values.put(KEY_ID,id);
    values.put(KEY_IMAGE,imag);
    values.put(KEY_STATUS,status);
    values.put(KEY_UPLOADSTATUS,uploadstatus);
    values.put(KEY_USERID,userid);
    // Inserting Row
    db.insert(TABLE_LABELS, null, values);
    db.close(); // Closing database connection
}
public ArrayList<BuisnesslistItems> getAllLabels(){
    //  List<String> labels = new ArrayList<String>();
    ArrayList<BuisnesslistItems>labels=new ArrayList<BuisnesslistItems>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {

            BuisnesslistItems buisnesslistItems=new BuisnesslistItems();
            buisnesslistItems.setImage(cursor.getBlob(1));
            buisnesslistItems.setStatus("Status:"+cursor.getString(2));


            labels.add(buisnesslistItems);
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return labels;
}

public String composeJSONfromSQLite(){
    ArrayList<HashMap<String, String>> label;
    label = new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM labels where " + KEY_STATUS + " = '"+"no"+"'";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        String encodedImage = Base64.encodeToString(cursor.getBlob(1), Base64.DEFAULT);
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(KEY_ID, cursor.getString(0));
            map.put(KEY_IMAGE, encodedImage);
            map.put(KEY_USERID,cursor.getString(4));
            map.put(KEY_STATUS,"yes");
            label.add(map);
        } while (cursor.moveToNext());
    }
    database.close();
    Gson gson = new GsonBuilder().create();
    //Use GSON to serialize Array List to JSON
    return gson.toJson(label);
}

/**
 * Get Sync status of SQLite
 * @return
 */
public String getSyncStatus(){
    String msg = null;
    if(this.dbSyncCount() == 0){
        msg = "Wallet is Sync with cloud!";
    }else{
        msg = "Wallet needs to be Sync\n";
    }
    return msg;
}

/**
 * Get SQLite records that are yet to be Synced
 * @return
 */
public int dbSyncCount(){
    int count = 0;
    String selectQuery = "SELECT  * FROM labels where " +KEY_STATUS+" = '"+"no"+"'";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    count = cursor.getCount();
    database.close();
    return count;
}

/**
 * Update Sync status against each User ID
 * @param id
 * @param status
 */
public void updateSyncStatus(String id, String status){
    SQLiteDatabase database = this.getWritableDatabase();
    String updateQuery = "Update labels set " + KEY_STATUS + " = '"+ status +"'," + KEY_UPLOADSTATUS + " = 'Uploaded' where " + KEY_ID + "="+"'"+ id +"'";
    Log.d("query", updateQuery);
    database.execSQL(updateQuery);
    database.close();
}
public void deleteUploaded(String status){
    SQLiteDatabase database=this.getWritableDatabase();
    String deleteQuery="Delete From labels where " + KEY_STATUS+ " = 'yes' ";
    Log.d("dquery",deleteQuery);
    database.execSQL(deleteQuery);
    database.close();
}

列表页:

BuisnessDatabaseHandler db = new BuisnessDatabaseHandler(getApplicationContext());

    // Spinner Drop down elements
    //  List<String> lables = db.getAllLabels();
    ArrayList<BuisnesslistItems>list=new ArrayList<BuisnesslistItems>();
    list=db.getAllLabels();
    buisnessListAdapter = new BuisnessListAdapter(
            BuisnessList.this, list);
    if (loginSession.isLoggedIn()) {
        loginSession.checkLogin();
        listView.setAdapter(buisnessListAdapter);
        listView.setEmptyView(findViewById(R.id.empty));

        Toast.makeText(getApplicationContext(), db.getSyncStatus(), Toast.LENGTH_LONG).show();
    }else{
        Intent i=new Intent(BuisnessList.this,LoginPAge.class);
        startActivity(i);
        BuisnessList.this.finish();
    }

错误:

 Caused by: android.database.sqlite.SQLiteException: no such table: buisnesslabels (code 1): , while compiling: SELECT  * FROM buisnesslabels
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
        at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1346)
        at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1285)
        at nidhinkumar.reccs.buisnesscarddetails.BuisnessDatabaseHandler.getAllLabels(BuisnessDatabaseHandler.java:81)
        at nidhinkumar.reccs.buisnesscarddetails.BuisnessList.syncSQLiteMySQLDB(BuisnessList.java:364)
        at nidhinkumar.reccs.buisnesscarddetails.BuisnessList.init(BuisnessList.java:216)
        at nidhinkumar.reccs.buisnesscarddetails.BuisnessList.onCreate(BuisnessList.java:143)

我想在列表页面中添加一个条件来检查表是否存在以及是否有值

【问题讨论】:

  • 为什么这个问题被标记为mysql(它是免费的、开源的、跨平台的RDBMS服务器软件——与SQLite完全无关)?

标签: android sqlite


【解决方案1】:

您可以使用以下语句来检查表是否存在:

Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"
    + TABLE_NAME + "'", null);

SQLite 维护一个名为 sqlite_master 的表,其中包含数据库中所有表的信息。因此,如果生成的游标返回计数 1,您就知道该表存在。检查后,使用所需的查询再次查询数据库:

cursor = your-query-here; 

然后再次使用cursor.getCount(); 来确定您是否有数据。如果cursor.getCount(); 返回的值大于 0,那么您就有了您想要的数据。

【讨论】:

  • 谢谢丹尼尔。这很好用。 :)
【解决方案2】:

SQLite 语句:

SELECT * FROM sqlite_master WHERE name ='tablename' and type='table';

打电话

db.rawQuery() 

并阅读光标或

SQLiteStatement s = db.compileStatement(SQLiteStatement);
long count = s.simpleQueryForLong();

如果(计数 > 0) -> 表存在

检查它是否存在后,您可以查询行数等。也许您必须检查表中是否存在特定列

【讨论】:

    【解决方案3】:

    手动方式

    访问以下链接并下载 DBrowser:Sqlite DBBrowser

    现在,转到 Android 设备监视器

    • 展开数据
    • 再次展开其中的数据
    • 然后使用您的应用程序包名称搜索文件夹
    • 然后打开里面的数据库文件夹
    • 将该数据库文件展开并拉取到本地,同时拉取以.sqlite 扩展名保存
    • 打开 DBBrowser 并打开您在本地拥有的数据库。
    • 您现在可以检查表是否已创建或其中是否包含行。

    编辑

    DATABASE_VERSION = 1 更改为DATABASE_VERSION = 2 因此,每当您更改 onCreate()onUpgrade() 中的任何内容时,请增加数据库版本。

    要检查你的表是否有行,

    if(list.size() == 0){
       // empty
    }
    

    【讨论】:

    • 不,我想检查表是否有值的条件,如果没有值,那么它应该显示一些消息以将值添加到数据库中,我不想使用查看数据库sqlite 浏览器
    • 检查一次编辑并尝试一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多