下午,我正在编写一个数据库管理程序,以方便工作。如果表没有返回结果,我在使用datareader时遇到问题。我已经在网上搜索了一个解决方案,但无济于事。所以我正在吃谦卑的馅饼并问。
首先,您了解数据库布局,我们有多个表,我想在一个列表视图中显示结果。代码适用于显示整个表,但是当尝试搜索时,在第一个表中找不到结果,那么它会为循环中的每个表抛出一个异常。但是如果在第一个表中找到结果,它将继续循环,直到在每个表中找不到搜索字符串。
这是代码
private string _strDBPath;
private string _strContractNumber;
public string[] dbTables = new string[9] {"0", "1800", "2800", "4000", "5000", "5400", "5700", "6800", "7800"};
public string[] dbFields = new string[3] { "ContractNumber", "Name", "REF",};
private enum sqlType {Normal, Search}
private bool dbSearch =false;
private void frmRecords_Load(object sender, EventArgs e)
{
lstContractsAddColums();
timerStart.Start();
}
private void lstContractsAddColums()
{
lstContracts.Columns.Clear();
for (int i = 0; i < dbFields.Length; i++) //Check to see if last field in array
lstContracts.Columns.Add(dbFields[i], 200, HorizontalAlignment.Left);
}
private void timerStart_Tick(object sender, EventArgs e)
{
for (int i = 0; i < dbTables.Length; i++)
{
while (!dbSearch == false)
{
}
dbGetData(i, sqlType.Search, "1000", "ContractNumber");
dbSearch = false;
}
timerStart.Stop();
}
private void dbGetData(int dbTable, sqlType sqlRecords, string strSearch, string strField)
{
string mySQL = "SELECT ";
for (int i = 0; i < dbFields.Length; i++) //Check to see if last field in array
if (i < dbFields.Length - 1)
{
mySQL = mySQL + dbFields[i] + ", "; //This is not the last field
}
else
{
mySQL = mySQL + dbFields[i] + " "; //This is the last field (No commor required)
}
switch (sqlRecords)
{
case sqlType.Normal:
mySQL = mySQL + " From " + dbTables[dbTable] + " ORDER BY ContractNumber"; //Adds the last part of the sayntex
break;
case sqlType.Search:
mySQL = mySQL + " From " + dbTables[dbTable] + " WHERE " + strField + " = " + strSearch; //Adds the last part of the sayntex
break;
default:
mySQL = mySQL + " From " + dbTables[dbTable] + " ORDER BY ContractNumber"; //Adds the last part of the sayntex
break;
}
ConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strDBPath + ";Jet OLEDB:Database Password="; //Selects the database along with the provider of the database
try
{
using(OleDbConnection MyConn = new OleDbConnection(ConnStr) )
{
MyConn.Open(); //opens MyConn
OleDbCommand Cmd = new OleDbCommand(mySQL, MyConn);
OleDbDataReader ObjReader = Cmd.ExecuteReader();
if (!ObjReader.HasRows)
{
MessageBox.Show("No rows found");
}
else
{
while (ObjReader.Read())
{
ListViewItem item = new ListViewItem(ObjReader[dbFields[0].ToString()].ToString());
for (int i = 1; i < dbFields.Length; i++) //Check to see if last field in array
item.SubItems.Add(ObjReader[dbFields[i]].ToString());
lstContracts.Items.Add(item);
}
}
dbSearch = true;
ObjReader.Close();
Cmd.Dispose();
MyConn.Close();
}
}
catch (Exception ex)
{
oErrorLog.WriteErrorLog(ex.ToString());
dbSearch = true;
}
finally
{
dbSearch = true;
}
}
这可能是愚蠢的,但任何建议都可以提供帮助。