我正在編寫一個程序,其中有大量的.mdb文件,我需要能夠連接到每個文件並搜索它們並根據數據庫中的值檢查用戶數據。我不想硬編碼每個連接,因爲數據庫包含特定位置的防火牆信息和規則,網絡管理員在這裏傾向於將更多的訪問文件添加到文件夾中,並且不得不去改變程序的源代碼代碼每次發生這種情況。特別是一旦項目不再在我手中,另一位開發人員就不得不爲此工作。C# - 動態訪問Microsft Access數據庫文件(.mdb)的列表並打開它們以搜索數據
現在,我創建了一個函數,該函數創建以當前目錄中的.mdb或.ldb擴展名結尾的文件(各種)文件列表。我也有一個文件名的字符串數組,並用消息框輸出它們來確認方法背後的一般想法。該程序能夠正確列出每個文件的擴展名爲.mdb的名稱,所以我知道它至少可以在使用該擴展名拉取每個文件時使用。現在我面臨循環的問題,並打開每個數據庫來提取我需要的信息。這是我困惑的地方。下面是迄今爲止功能:
private void SelectDstIPTable()
{
//Write SQL code to select table
//Select the table and pull the info
//Do something?
//Sort?
//Does this need to be moved out of the method scope to the whole class?
string strQuery = "SELECT * FROM devices WHERE dst_IP like '% " + textBox1.Text + "%' OR src_ip Like '%" + textBox1.Text + "%'";
//This will be the list of files that end in .mbd that the code will loop through looking for the IP
string currentDirectory = Directory.GetCurrentDirectory();
var ext = new List<string> { "mdb", "ldb" };
var myFiles = Directory.GetFiles(currentDirectory, "*.*", SearchOption.AllDirectories).Where(s => ext.Contains(Path.GetExtension(s)));
string[] fileArray = Directory.GetFiles(currentDirectory, "*.mdb", SearchOption.AllDirectories);
string allNames = "";
//Just confirmation that this actually works
foreach (string name in fileArray)
{
allNames += name + "\n";
}
MessageBox.Show(allNames);
//Now we actually need to do something
}
我也有規定了特定數據庫的連接,以確保我的代碼檢查數據庫的信息是有效的另一個函數。不幸的是,這不是該情況下,或者但這裏的相關代碼反正:
private string connParam = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PathToDatabaseFile.mdb";
private void OpenConnection()
{
firewallConn.ConnectionString = connParam;
firewallConn.Open();
successfulConnection = true;
MessageBox.Show("Connection successful!");
}
private void EstablishConnection()
{
//There's a slight delay in making the connection now that I wrapped it in exception handling
//TODO: Try to speed that up and figure out why it was slowed down by a noticable ammount
try
{
if (firewallConn != null && firewallConn.State == ConnectionState.Closed)
OpenConnection();
else
MessageBox.Show("The connection has already been established.\nType ''Close me'' to close the connection.");
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
如果需要任何更多的細節,只是讓我知道,我會提供我所能。
忘記循環一分鐘。你知道如何打開一個.mdb文件嗎? – elyashiv
它不應該很難使這更動態,只需更改連接字符串,嘗試打開,如果失敗,跳過,如果成功。 – BugFinder
@Elyashiv是的 - 我添加了相關的代碼。當我刪除發佈的一些評論時,firewallConn.ConnectionString被意外刪除。我修正了這一點。它成功連接到單個數據庫。 – Ryan