I am using System.Data.SQLite
. I am writing a C# program that reads data from any given SQLite database. This program runs a number of queries over the given database. I query the sqlite_master
table to determine the tables in the database and then run PRAGMA
statements to get the schema of each of the tables.
My main problem is; when I do a SELECT * FROM table_1 JOIN table_2 ON table_1.id = table_2.id;
I cannot find a way to determine what table each of the id columns come from.
I am hoping that someone will be able to point me in the direction of being able to determine the table that each column in the query result is from.
I have been able to obtain the data in a NameValueCollection
which does not handle the duplicate column names in the way I would have liked. I would have liked a dictionary with the table name as a key with a dictionary of columns as the value; example below:
{"table_1": {"col_1": value, "col_2": value}, "table_2": {"col_1": value, "col_2": value}}
Or a qualified column name so I could access the items like:
reader["table_name.column_name"];
I have also been able to obtain the data from the query in a DataTable, which does not obtain the data in a way I would have liked. The id column from the example above is simply appended with a number 1 to indicate that it is duplicate.
The two functions I use to return the NameValueCollections and DataTable are below:
class DatabaseReader
{
private string ConnectionString;
public DatabaseReader(string ConnectionString)
{
this.ConnectionString = ConnectionString;
}
/// <summary>
/// Returns a NameValueCollection of the query result
/// </summary>
/// <param name="query">The query to be run</param>
public IEnumerable<NameValueCollection> ExecuteReader(string query)
{
SQLiteCommand command = new SQLiteCommand();
command.CommandText = query;
using (SQLiteConnection conn = new SQLiteConnection(this.ConnectionString))
{
conn.Open();
// Do things with the open connection
command.Connection = conn;
SQLiteDataReader reader;
using (command)
{
reader = command.ExecuteReader();
}
if (reader != null)
{
while (reader.Read())
{
yield return reader.GetValues();
}
}
else
{
throw new Exception(string.Format("{0} query returned nothing"));
}
}
}
/// <summary>
/// Returns a DataTable of the query result
/// </summary>
/// <param name="query">The query to be run</param>
public DataTable GetDataTable(string query)
{
DataTable dt = new DataTable();
try
{
using (SQLiteConnection cnn = new SQLiteConnection(this.ConnectionString))
{
cnn.Open();
using (SQLiteCommand mycommand = new SQLiteCommand(cnn))
{
mycommand.CommandText = query;
using (SQLiteDataReader reader = mycommand.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}
}
cnn.Close();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return dt;
}
}
Any help is greatly appreciated! :)
Aucun commentaire:
Enregistrer un commentaire