2016-08-22 41 views
0

我正在使用xamarin和sqlite制作一个android应用程序。我想按钮add连接数据库testdb.sqliteuser但调试我的平板电脑的应用程序,我得到这个错误:使用sqlite在xamarin中连接表格

SQLite.SQLiteException: Could not open database file: /storage/emulated/0/testdb.sqlite/testdb.sqlite (CannotOpen)

我的代码是:

button_add.Click += delegate 
{ 
    ring dbName = "testdb.sqlite"; 

    /// Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 
    string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName); 

    // Check if your DB has already been extracted. 
    if (!File.Exists(dbPath)) 
    { 
     using (BinaryReader br = new BinaryReader(Assets.Open(dbName))) 
     { 
      using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create))) 
      { 
       byte[] buffer = new byte[2048]; 
       int len = 0; 
       while ((len = br.Read(buffer, 0, buffer.Length)) > 0) 
       { 
        bw.Write(buffer, 0, len); 
       } 
      } 
     } 
    } 

    editemail.Text = "I love coding"; 
    // db.createdatabase(); 

    //folder_loc.Text = folder; 
    using (var connection = new SQLiteConnection(System.IO.Path.Combine(dbPath, dbName))) 
    { 
     // connection.CreateTable<person>(); 

     //string query = "select * from test"; 
     // connection.Query <test> (query); 


     var query = connection.Table<user>(); 

     foreach (var stock in query) 
     { 
      Console.WriteLine("Stock: " + stock.name); 
      editname.Text = stock.name; 
     } 
    } 
}; 

user声明:

public class user 
{ 
    public int id { get; set; } 

    //public string email { get; set; } 

    public string name { get; set; } 

    //public string gender { get; set; } 
} 

回答

1

那么,你在代码中定义了两次名字,一次在这里:

string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName); 

,然后当你想打开它,你使用DBPATH,数据库名,要么删除DBNAME参考:

string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName); 

或:

(var connection = new SQLiteConnection(System.IO.Path.Combine(dbPath, dbName))) 

,它应该工作;)

+0

仍然会出现相同的错误 – Nidzzz

+0

我用'dbpath'1st创建数据库和一个连接 – Nidzzz

+0

你的代码你结束了p后请尝试 –