我成功地使用了 try - catch 方法來測驗 C# 與公共資料庫的連接。但是,在 SQLite 的情況下,當未檢測到資料庫時,它會創建一個新資料庫,這在我的情況下是不需要的。“當你連接到一個不存在的 SQLite 資料庫檔案時,SQLite 會自動為你創建新的資料庫”
SQLiteDataAdapter ad;
DataTable dt = new DataTable();
try
{
sqlite = new SQLiteConnection("Data Source=C:/Users/SKUL/Desktop/db/PatHist.db");
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
//-----------------
picConnectionStatus.Image = Properties.Resources.icons8_database_view_64;
lblConnectionEstablished.Text = "Connection Established";
sqlite.Close();
}
catch (Exception ex)
{
picConnectionStatus.Image = Properties.Resources.icons8_delete_database_64;
lblConnectionEstablished.Text = "Connection Error";
lblConnectionEstablished.ForeColor = System.Drawing.Color.Red;
}
需要以某種方式禁用自動創建資料庫并觸發“catch”例程
uj5u.com熱心網友回復:
在@Rafael 的建議之后,我檢查了檔案是否存在。做這個問題就解決了。
if (System.IO.File.Exists(@"C:\Users\SKUL\Desktop\db\nPatHist.db"))
{
sqlite = new SQLiteConnection("Data Source=C:\\Users\\SKUL\\Desktop\\db\\PatHist.db");
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
//-----------------
picConnectionStatus.Image = Properties.Resources.icons8_database_view_64;
lblConnectionEstablished.Text = "Connection Established";
sqlite.Close();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466309.html
