I wrote some code that should add database response to the List. it works on my PC, but does not work when I deploy my program to another PC.
I pinned down to my method. It stops working when it hits
int tot = rs.Fields.Count;
Here is my code:
public static List<List<String>> QUERY(String query, String dbPath)
{ ADODB.Connection cn = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset(); ADODB.Command cmdSQLData = new ADODB.Command();
List<List<String>> RETURNME = new List<List<String>>();
string cnStrOld = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=" + dbPath + ";Uid=;Pwd=;"; //does not work
string cnStr = @"Provider=Microsoft.JET.OLEDB.4.0; data source=" + dbPath;
cn.ConnectionTimeout = 0;
cn.Open(cnStr);
cn.CommandTimeout = 0;
rs.Open(query, cn);
while (rs.EOF == false) //GET HEADERNAMES, ADD TO LIST
{
List<String> A = new List<string>();
int tot = rs.Fields.Count;// calculating the amount of columns in the RS
for (int i = 0; i < tot; i++) //iterating through all columns and checking it's name
{
A.Add(rs.Fields[i].Name.ToString());
}
RETURNME.Add(A);
break;
}
while (rs.EOF == false)//GET DATA, ADD TO LIST
{
List<String> B = new List<string>(); //list of Data
int tot = rs.Fields.Count;// calculating the amount of columns in the RS
//Now we add query response
for (int i = 0; i < tot; i++) //iterating through all columns and checking it's name
{
B.Add(rs.Fields[i].Value.ToString());
}
RETURNME.Add(B);
rs.MoveNext();
}
rs.Close();
cn.Close();
return RETURNME;
}
I use relative paths and they are tested OK. I also have my try-catch staements (I removed them from here to shrink the code) and they indicate no errors. Somehow program is capable of entering to “while (rs.EOF == false)” statement, so I assume that records are returned?
Could you please assist?
I ended up with the following solution:
public static List<List<String>> QUERY_TEST(String query, String dbPath)
{
List<List<String>> RETURNME = new List<List<String>>();
String cnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbPath + ";Jet OLEDB:Database Password=;";
OleDbDataAdapter Data1 = new OleDbDataAdapter(query, cnStr);
DataSet a = new DataSet();
Data1.Fill(a);
DataTable dt = a.Tables[0];
//Adding column names to the first row on the list
List<String> B = new List<string>();
foreach (DataColumn dr in dt.Columns)
{
List<String> A = new List<string>();
B.Add(dr.Caption.ToString());
}
RETURNME.Add(B);
//Adding data to the columns
foreach (DataRow dr in dt.Rows)
{
List<String> A = new List<string>();
for (int i = 0; i < dt.Columns.Count; i++)
{
A.Add(dr[i].ToString());
}
RETURNME.Add(A);
break;
}
return RETURNME;
}
basically this is what you could do.. of course you need to replace certain things with your variable names where necessary