【问题标题】:Not getting new created table from the database没有从数据库中获取新创建的表
【发布时间】:2011-11-08 03:37:41
【问题描述】:

我的数据库适配器代码如下:

package com.quiz.spellingquiz;
import java.io.IOException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DBAdapter 
{
    //  Database Operation
    public static final String KEY_ROWID = "_id";
    public static final String KEY_ISBN = "isbn";
    public static final String KEY_TITLE = "title";
    public static final String KEY_WORD = "word";
    public static final String KEY_SOUND = "sound";
    public static final String KEY_PUBLISHER = "publisher";    
    private static final String TAG = "DBAdapter";
    private static final String DATABASE_NAME = "testing";
    public static String DATABASE_TABLE = null;
    private static final int DATABASE_VERSION = 1;

    public static final String DATABASE_CREATE =
        "create table "+DATABASE_TABLE+" (_id integer primary key, "
        + "isbn text not null," 
        + "title text not null,"
        + "word text not null,"
        + "sound text not null,"
        + "publisher text not null);";


    private final Context context; 

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;


    public DBAdapter(Context ctx, String table_name) 
    {
        this.context = ctx;
        DATABASE_TABLE=table_name;
        DBHelper = new DatabaseHelper(context);
    }

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

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) 
        {
            Log.w(TAG, "Upgrading database from version "+oldVersion+" to "+newVersion+", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
            onCreate(db);
        }
    }    

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }

    //---insert a title into the database---
    public long insertTitle(String isbn, String title, String word, String sound, String publisher) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ISBN, isbn);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_WORD, word);
        initialValues.put(KEY_SOUND, sound);
        initialValues.put(KEY_PUBLISHER, publisher);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular title---
    public boolean deleteTitle(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public boolean deleteAllTitle()
    {
        return db.delete(DATABASE_TABLE,null, null)>0;
    }
    public Cursor getAllTitles() 
    {
        Cursor mCursor = db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_ISBN,
                KEY_TITLE,
                KEY_WORD,
                KEY_SOUND,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null,
                null, 
                null,
                null);

        return mCursor;
    }


    //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException 
    {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                        KEY_ROWID,
                        KEY_ISBN, 
                        KEY_TITLE,
                        KEY_WORD,
                        KEY_SOUND,
                        KEY_PUBLISHER
                        }, 
                        KEY_ROWID + "=" + rowId, 
                        null,
                        null, 
                        null, 
                        null, ////////////////////////////
                        null);
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    // to fetch TextFile with Sound file
    public Cursor getSound(String str) throws SQLException
    {
        String file = Environment.getExternalStorageDirectory().getAbsolutePath();
        file = file+"/"+str+".3gp";

        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_ISBN, 
                    KEY_TITLE,
                    KEY_WORD,
                    KEY_SOUND,
                    KEY_PUBLISHER
                }, 
                KEY_SOUND + "=" +file, 
                null,
                null, 
                null, 
                null,
                null);
if (mCursor != null) 
{
    mCursor.moveToFirst();
}
return mCursor;

    }

    public void deleteAll()
    {
        this.db.delete(DATABASE_TABLE, null, null);
    }

    //---updates a title---
    public boolean updateTitle(long rowId, String isbn, String title,String word,String sound, String publisher) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_ISBN, isbn);
        args.put(KEY_TITLE, title);
        args.put(KEY_WORD, word);
        args.put(KEY_SOUND, sound);
        args.put(KEY_PUBLISHER, publisher);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

现在在另一个活动中,我使用如下表名创建 DatabaseAdapter 对象:

final DBAdapter db = new DBAdapter(this,table_name); // create new database with givan table name

现在,当我从该对象获取数据时,它给了我这样的错误:

android.database.sqlite.SQLiteException: no such table: hello: , while compiling: INSERT INTO hello(word, title, sound, publisher, isbn) VALUES(?, ?, ?, ?, ?);

那么我哪里错了?为什么我无法创建表?我该怎么办?

查看这是我调用 DBAdapter 的另一个活动的代码

  // database object        
    final DBAdapter db = new DBAdapter(this); // create new database with givan table name


    showall.setOnClickListener(new View.OnClickListener() 
    {

        public void onClick(View v) 
        {
            db.open();
            Cursor c = db.getAllTitles();
            while(c.moveToNext())        
            {
                Toast.makeText(EnterWordsActivity.this,
                        "id: " + c.getString(0) + "\n" + 
                        "ISBN: " + c.getString(1) + "\n" +  
                        "TITLE: " + c.getString(2) + "\n" + 
                        "WORD: " + c.getString(3) + "\n" +
                        "SOUND:" + c.getString(4) +"\n"+
                        "PUBLISHER:  " + c.getString(5),Toast.LENGTH_LONG).show();
            }
            db.close();
        }
    });

在同一数据库中创建新表后的错误日志。

09-01 15:05:52.608: ERROR/AndroidRuntime(596): FATAL EXCEPTION: main

09-01 15:05:52.608: ERROR/AndroidRuntime(596): android.database.sqlite.SQLiteException: no such table: world: , while compile: SELECT _id, isbn, title, word, sound, publisher FROM世界 09-01 15:05:52.608:错误/AndroidRuntime(596):在 android.database.sqlite.SQLiteCompiledSql.native_compile(本机方法) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteCompiledSql.(SQLiteCompiledSql.java:64) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:80) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:46) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1229) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1184) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1301) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 com.quiz.spellingquiz.DBAdapter.getAllTitles(DBAdapter.java:119) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 com.quiz.spellingquiz.EnterWordsActivity$1.onClick(EnterWordsActivity.java:86) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.view.View.performClick(View.java:2408) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.view.View$PerformClick.run(View.java:8816) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.os.Handler.handleCallback(Handler.java:587) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.os.Handler.dispatchMessage(Handler.java:92) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.os.Looper.loop(Looper.java:123) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 android.app.ActivityThread.main(ActivityThread.java:4627) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 java.lang.reflect.Method.invokeNative(Native Method) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 java.lang.reflect.Method.invoke(Method.java:521) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-01 15:05:52.608: 错误/AndroidRuntime(596): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-01 15:05:52.608: 错误/AndroidRuntime(596): at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

    标签: android android-layout android-emulator android-widget android-ndk


    【解决方案1】:

    我认为这里的问题是您没有为您的数据库名称声明 .db 扩展名

     private static final String DATABASE_NAME = "testing";
    

    应该是

     private static final String DATABASE_NAME = "testing.db";
    

    这肯定行得通,因为我试过你的代码。

    还有一个变化是这样的

    @Override
            public void onCreate(SQLiteDatabase db) 
            {
                db.execSQL("create table "+DATABASE_TABLE+" (_id integer primary key, "
                        + "isbn text not null," 
                        + "title text not null,"
                        + "word text not null,"
                        + "sound text not null,"
                        + "publisher text not null);");
            }
    

    添加上面的代码而不是

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

    那么就这样调用这个类,

    DBAdapter adapter = new DBAdapter(this,"mytable");
    

    【讨论】:

    • 好的。谢谢回复。但是请参阅我更新的问题,我将一些代码放在我要创建和调用 DBAdapter 对象的位置。那么,如果我还想将表名提供给 DBAdapter 类,我应该怎么做???然后应该只使用该名称创建表。
    • 我已经解决了你的问题。就按照我的回答去做,你就完成了,然后打电话给你的班级。
    • 是的,苏瑞。 . . .非常感谢。所以在这种情况下每次表都会是新的吧???
    • 好吧,我还没有在数据库上做那么多工作。也谢谢你。
    • 这里有一个问题。 ..如果我创建新数据库和新表,那么它工作得很好,但是如果我在该数据库中创建新表,那么它就会崩溃并告诉我没有带有新添加名称的这样的表?现在我哪里错了?
    【解决方案2】:

    使用此代码

     import java.io.IOException;
    
    import  android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.media.MediaPlayer;
    import android.media.MediaRecorder;
    import android.os.Environment;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class DBAdapter 
    {
    //  Database Operation
    public static final String KEY_ROWID = "_id";
    public static final String KEY_ISBN = "isbn";
    public static final String KEY_TITLE = "title";
    public static final String KEY_WORD = "word";
    public static final String KEY_SOUND = "sound";
    public static final String KEY_PUBLISHER = "publisher";    
    private static final String TAG = "DBAdapter";
    private static final String DATABASE_NAME = "testing";
    public static String DATABASE_TABLE = null;
    private static final int DATABASE_VERSION = 1;
    
    public static final String DATABASE_CREATE =
        "create table "+DATABASE_TABLE+" (_id integer primary key, "
        + "isbn text not null," 
        + "title text not null,"
        + "word text not null,"
        + "sound text not null,"
        + "publisher text not null);";
    
    
    private final Context context; 
    
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;
    
    
    public DBAdapter(Context ctx, String table_name) 
    {
        this.context = ctx;
        DATABASE_TABLE=table_name;
        DBHelper = new DatabaseHelper(context);
    }
    
    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);
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) 
        {
            Log.w(TAG, "Upgrading database from version "+oldVersion+" to "+newVersion+", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
            onCreate(db);
        }
    }    
    
    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }
    
    //---closes the database---    
    public void close() 
    {
        DBHelper.close();
    }
    
    //used to create the the new table
    public void createNewTable(String t_name){
        this.DATABASE_TABLE=t_name;
        db.execSQL(this.DATABASE_CREATE);
    }
    
    
    //---insert a title into the database---
    public long insertTitle(String isbn, String title, String word, String sound, String publisher) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ISBN, isbn);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_WORD, word);
        initialValues.put(KEY_SOUND, sound);
        initialValues.put(KEY_PUBLISHER, publisher);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }
    
    //---deletes a particular title---
    public boolean deleteTitle(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public boolean deleteAllTitle()
    {
        return db.delete(DATABASE_TABLE,null, null)>0;
    }
    public Cursor getAllTitles() 
    {
        Cursor mCursor = db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_ISBN,
                KEY_TITLE,
                KEY_WORD,
                KEY_SOUND,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null,
                null, 
                null,
                null);
    
        return mCursor;
    }
    
    
    //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException 
    {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                        KEY_ROWID,
                        KEY_ISBN, 
                        KEY_TITLE,
                        KEY_WORD,
                        KEY_SOUND,
                        KEY_PUBLISHER
                        }, 
                        KEY_ROWID + "=" + rowId, 
                        null,
                        null, 
                        null, 
                        null, ////////////////////////////
                        null);
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    // to fetch TextFile with Sound file
    public Cursor getSound(String str) throws SQLException
    {
        String file = Environment.getExternalStorageDirectory().getAbsolutePath();
        file = file+"/"+str+".3gp";
    
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_ISBN, 
                    KEY_TITLE,
                    KEY_WORD,
                    KEY_SOUND,
                    KEY_PUBLISHER
                }, 
                KEY_SOUND + "=" +file, 
                null,
                null, 
                null, 
                null,
                null);
        if (mCursor != null) 
      { 
       mCursor.moveToFirst();
      }
     return mCursor;
    
    }
    
    public void deleteAll()
    {
        this.db.delete(DATABASE_TABLE, null, null);
    }
    
    //---updates a title---
    public boolean updateTitle(long rowId, String isbn, String title,String word,String sound, String publisher) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_ISBN, isbn);
        args.put(KEY_TITLE, title);
        args.put(KEY_WORD, word);
        args.put(KEY_SOUND, sound);
        args.put(KEY_PUBLISHER, publisher);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    

    }

    在你的活动中

    db.open();
          db.createNewTable("ur table name");
    

    这解决了你的问题

    【讨论】:

    • 是的,它工作正常,现在我可以在现有数据库中创建新表。但是第一个创建的表呢?
    • 旧表丢失还是保存在数据库中?我怎么知道呢?
    • 我仍然没有得到你的答案,我之前创建的旧表是什么?因为我看不到它。 . .
    • 旧表还在数据库中
    • 是的,我已经检查过了。伟大的。谢谢。你能帮我多一点吗??我想在数据库中显示所有可用的表?怎么可能?或者有没有可能?
    【解决方案3】:

    一开始,当final string DATABASE_CREATE 被创建时,string DATABASE_TABLE 将是null。所以每次使用DATABASE_CREATE,查询是:

    DATABASE_CREATE = "create table (_id integer primary key, "
        + "isbn text not null," 
        + "title text not null,"
        + "word text not null,"
        + "sound text not null,"
        + "publisher text not null);"
    

    这个查询(没有表名)无效。

    === 更新 ===

    string DATABASE_CREATE 中将变量DATABASE_TABLE 替换为模板名称:

    public static final String DATABASE_CREATE =
        "create table #table_name# (_id integer primary key, "
        + "isbn text not null," 
        + "title text not null,"
        + "word text not null,"
        + "sound text not null,"
        + "publisher text not null);";
    

    并替换onCreate中的模板名称:

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        String query = DATABASE_CREATE.replace("#table_name#", DATABASE_TABLE);
        db.execSQL(query);
    }
    

    【讨论】:

    • 好的。那我该怎么办?请参考我的整个程序。我在从其他活动创建 DatabaseAdapter 时给出了表名。
    • @iDroid Explorer 首先删除 DATABASE_TABLE = null;并尝试使用 DATABASE_TABLE = "";
    • @scessor :它不工作。 :-( 它给了我像无效令牌这样的错误。
    • 如果您使用'#table_name#'请在onCreate()中替换为"#table_name#"
    • 我仍然无法创建该表。 Lkistern table_name 是我在调用 Databaseadapter 时传递的值。请参阅 DatabaseAdatpeter 的构造函数。
    【解决方案4】:

    如果您的新更改设置未显示,那么我认为您应该更新数据库版本。 这将执行新的更改并保存它们

    【讨论】:

      猜你喜欢
      • 2022-06-16
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多