2012-04-18 95 views
0

我遇到了一个小问题,与我目前的项目。我正在做一个android应用程序,它需要连接到SQLite数据库来处理一些语句。我相信这些陈述等都很好,我唯一的问题是与数据库的连接不成功。Android SQLite数据库连接不成功

logcat的错误:

04-18 08:20:30.688: E/Database(304): sqlite3_open_v2("jdbc:sqlite:res/raw/randomdb.db", &handle, 1, NULL) failed 

所以到目前为止我的代码,用于连接到数据库是这样的:

String url = "jdbc:sqlite:res/raw/randomdb.db"; 
      SQLiteDatabase db; 
      db = SQLiteDatabase.openDatabase(url, null, SQLiteDatabase.OPEN_READONLY); 

正如你可以看到,我试图存取权限位于数据库在我的项目/ res/raw文件夹中。有没有人看到错误?

!!!更新! * 我试图用SQLiteOpenHelper的方式,但仍然鼓励一个错误,我似乎无法解决。这是我的新代码: *

public class DatabaseAdapter extends SQLiteOpenHelper { 
    private static String dbPath= "data/data/com.YourPackageName/applicationDb/"; 
    private static String dbName = "YourDBName"; 
    private SQLiteDatabase applicationDatabase; 
    private final Context applicationContext; 

    private boolean checkDataBase(){ 
     File dbFile = new File(dbPath + dbName); 
     return dbFile.exists(); 
    } 

    public void openDataBase() throws SQLException{ 
     String fullDbPath= dbPath + dbName; 
     applicationDatabase = SQLiteDatabase.openDatabase(fullDbPath,null,SQLiteDatabase.OPEN_READONLY); 
    } 

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

我得到这个错误: 隐超构造SQLiteOpenHelper()是未定义默认构造函数。必须定义一个明确的构造函数 任何想法?会很好!

如果你想连接你与SQLite数据库Android应用

回答

0

,那么你需要扩展SQLiteOpenHelper

public class AbcClass extends SQLiteOpenHelper 

之后,你需要重写这些方法: 的onCreateonUpgrade 和构造AbcClass的看起来像:

public AbcClass(Context context) { 
    super(context, DB_NAME, null, VERSION); //public static final String DB_NAME = "test.sqlite"; 
} 
0
public boolean databaseExist() 
    { 
     File dbFile = new File(DB_PATH + DB_NAME); 
     return dbFile.exists(); 
    } 

This is the solution... 

OR -----------------------

private boolean checkDataBase(){ 

    SQLiteDatabase checkDB = null; 

    try{ 
     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

    }catch(SQLiteException e){ 

     //database does't exist yet. 

    } 

    if(checkDB != null){ 

     checkDB.close(); 

    } 

    return checkDB != null ? true : false; 
} 
0

我想你指定的路径不正确的,因此作为一个提到的其他答案没有找到数据库。但是我从未使用openDatabase方法从raw文件夹中读取,因此我不知道哪个是正确的路径。

不过曾经有一段时间我已经把数据库和我的应用程序一起发货了。它位于assets文件夹中,一旦应用程序启动,我将它复制到私有应用程序存储器中(非常类似于使用SqliteOpenHelper创建的任何数据库)。从那时起,我用通常的方式与SqliteOpenHelper访问数据库。

基本上,我跟着这个thread中提到的博客,因为我的数据库文件大于1MB,我使用了thread中描述的技术。希望将这两者结合起来,您将使数据库运行!

编辑顺便说一句,你就错了,openDatabase不接受URL,但路径。