2011-11-20 100 views
2

我正在開發使用Monotouch的iPhone應用程序。我需要訪問一個Sqlite數據庫。在我的精神,我有一個合同,數據訪問,業務訪問和UI項目。我有兩個問題:iPhone - 連接字符串和DB文件

  1. 我應該在哪裏保存我的DB文件?最初,我把它放在數據訪問項目中。當我編譯我的業務訪問項目時,它將數據庫文件複製到輸出中,但是當我編譯我的UI項目時,它不會(UI具有涉及數據訪問的業務訪問的引用)。我將它移到了UI項目中,但將它保留在那裏感覺不對。

  2. 我應該在哪裏給DB保留連接字符串?有配置文件的概念嗎?

回答

2

這裏是我們做什麼:

我們的船數據庫的副本中的應用。它包含在項目中的內容,始終複製。

在用戶的機器上,它存儲在特殊目錄Environment.SpecialFolder.Personal中。

當應用程序啓動時,我們檢查數據庫是否存在於用戶的系統上,如果沒有,則將其複製到那裏。

連接字符串只是"Data Source=" + sDatabasePath

這裏是我們使用這個代碼的樣本(我在連接東西,黑客攻擊,因爲我們使用一個自制類用於管理數據庫,但你應該明白我的意思):

const string DATABASE_FILE_NAME = "MyDB.db3"; 
bool fSuccess = false; 
DbConnection conn = new DbConnection(); 

string sApplicationDir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "MyApplicationSubDir"); 
if (!Directory.Exists (sApplicationDir)) { 
    Directory.CreateDirectory (sApplicationDir); 
} 

// Generate the directory to the database file 
string sDatabaseDir = Path.Combine (sApplicationDir, "Database"); 
m_sDatabaseDir = sDatabaseDir; 

if (!Directory.Exists (sDatabaseDir)) { 
    Directory.CreateDirectory (sDatabaseDir); 
} 

// Generate the path to the database file 
string sDatabasePath = Path.Combine (sDatabaseDir, DATABASE_FILE_NAME); 
m_sDatabaseFile = sDatabasePath; 

// If the file does not not exist 
if (!File.Exists (sDatabasePath)) { 
    // Copy the base implementation 
    File.Copy (Path.Combine (Path.Combine (Environment.CurrentDirectory, "Database"), DATABASE_FILE_NAME), sDatabasePath); 
} 

// Initialize the DB 
conn.ConnectionString = "Data Source=" + sDatabasePath; 
+0

感謝您的信息。爲了回答我的問題,我相信你1)把數據庫文件放在UI項目中2)沒有配置文件 – user472292

+0

是的,這是正確的。 –