android.database.sqlite.SQLiteException:没有这样的表:

时间:2016-04-28 17:16:00

标签: java android eclipse sqlite

在运行应用程序时我遇到了错误,虽然我检查了sqlite文件并且它包含了watchlist表,尽管该表没有条目。

DBAdapter.java

package hp.vamazon;

import android.content.ContentValues;   
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteOpenHelper;  
import android.util.Log;

public class DBAdapter {

    private static final String TAG = "DBAdapter"; //used for logging database version changes

    // Field Names:
    public static final String bookID = "bookid";//==KEYROW_ID
    public static final String bookName = "bookname";//==KEY_TASK
    public static final String bookPrice = "bbp";//==KEY_DATE
    public static final String storeName = "storename";

    public static final String[] ALL_KEYS = new String[] {bookID,bookPrice,bookName,storeName};

    // Column Numbers for each Field Name:
    public static final int COL_ROWID = 0;
    public static final int COL_TASK = 1;
    public static final int COL_DATE = 2;
    public static final int COL_STORE = 3;

    // DataBase info:
    public static final String DATABASE_NAME = "bookstore";
    public static final String DATABASE_TABLE = "watchlist";
    public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

    //SQL statement to create database
    private static final String DATABASE_CREATE_SQL = 
            "CREATE TABLE " + DATABASE_TABLE 
            + " (" + bookID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + bookName + " TEXT NOT NULL, "
            + bookPrice + " TEXT, "
            + bookPrice + " TEXT "
            + ");"; 

    private final Context context;
    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;


    public DBAdapter(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DBAdapter open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to be inserted into the database.
    public long insertRow(String bookname, String price,String id ,String store) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(bookID,id);   
        initialValues.put(bookPrice,price); 
        initialValues.put(bookName,bookname);
        initialValues.put(storeName,store);
        // Insert the data into the database.
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteRow(long rowId) {
        String where = bookID + "=" + rowId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(bookID);
        if (c.moveToFirst()) {
            do {
                deleteRow(c.getLong((int) rowId));              
            } while (c.moveToNext());
        }
        c.close();
    }

    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = bookID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Change an existing row to be equal to new data.
    public boolean updateRow(long rowId, String task, String date) {
        String where = bookID + "=" + rowId;
        ContentValues newValues = new ContentValues();
        newValues.put(bookName, task);
        newValues.put(bookPrice, date);
        // Insert it into the database.
        return db.update(DATABASE_TABLE, newValues, where, null) != 0;
    }


    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {  


db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
                }
    }


}

Watchlist.java

package hp.vamazon;

import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.List;  

import android.app.Activity;   
import android.database.Cursor;   
import android.os.Bundle;   
import android.support.v4.widget.SimpleCursorAdapter;   
import android.view.Menu;   
import android.view.MenuItem;   
import android.view.View;   
import android.widget.AdapterView;    
import android.widget.ListView;   

public class Watchlist extends Activity {


    DBAdapter myDb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watchlist);

        openDb();
        populatListViewFromDB();
    }
    private void openDb() {
        myDb=new DBAdapter(this);
        myDb.open();        
    }

    private void populatListViewFromDB() {


        Cursor cursor=myDb.getAllRows();

        startManagingCursor(cursor);

        String []fromFieldNames=new String[]{DBAdapter.bookName,DBAdapter.bookPrice,DBAdapter.storeName};
        int []toViewIDs=new int[]{R.id.item_name,R.id.item_price,R.id.item_store};

        SimpleCursorAdapter myCursorAdapter=new SimpleCursorAdapter(this,R.layout.cartitem_view
                ,cursor,fromFieldNames,toViewIDs);


        ListView myList=(ListView)findViewById(R.id.listView1);
        myList.setAdapter(myCursorAdapter);

    }
    private void registerClickCallback()
    {
        ListView myList=(ListView)findViewById(R.id.listView1);
        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor cursor=myDb.getRow(id);
            if(cursor.moveToFirst())
            {
                myDb.deleteRow(id);
                populatListViewFromDB();
            }
            cursor.close(); 
            }
        });
    }

}

at hp.vamazon.DBAdapter.getAllRows(DBAdapter.java:93)
at hp.vamazon.Watchlist.populatListViewFromDB(Watchlist.java:37)

4 个答案:

答案 0 :(得分:3)

扩展SQLiteOpenHelper的类应该在onCreate方法中执行sql命令来创建表,比如

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

是的,确定您已创建命令作为最终字符串DATABASE_CREATE_SQL来创建表但忘记了execute这样就不创建表。为了让您注意到您的onCreateonUpgrade方法都是空的。

通过扩展DatabaseHelper来查看here SQLiteOpenHelper的创建方式。

答案 1 :(得分:0)

  

android.database.sqlite.SQLiteException:没有这样的表

在你的情况下,这是因为你没有创建任何表格。在DatabaseHelper上,您应该包含onCreate()

来自文档:

  

首次创建数据库时调用。这是表的创建和表的初始填充的地方。

你应该在那里创建表格,如下所示:

db.execSQL(DATABASE_CREATE_SQL); //It will create the table

答案 2 :(得分:0)

您在DatabaseHelper类中的OnCreate和OnUpgrade方法中没有任何代码。 首先您需要执行execSQL命令来创建表:

@Override
        public void onCreate(SQLiteDatabase _db) {    
_db.execSQL(DATABASE_CREATE_SQL);  
        }

对于OnUpgrade方法,请参考以下代码:

     @Override 
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {

        String Query = "DROP TABLE IF EXISTS Your_Table_Name"
        _db.execSQL(Query);
        onCreate(_db);

                }

答案 3 :(得分:0)

我自己解决了这个问题,虽然感谢你的努力。问题是我没有在每个函数中定义SQLite数据库的新实例,这导致代码不抛出任何数据库异常,因为我们没有数据库。