2016-08-22 87 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後請嘗試 –