我正在使用System.Data.SQLite
。我正在编写一个C#程序,它从任何给定的SQLite数据库中读取数据。
该程序在给定数据库上运行许多查询。我查询sqlite_master
表以确定数据库中的表,然后运行PRAGMA
语句以获取每个表的模式。
我的主要问题是;当我执行SELECT * FROM table_1 JOIN table_2 ON table_1.id = table_2.id;
时,我无法找到确定每个id列来自哪个表的方法。
我希望有人能指出我能够确定查询结果中每一列的表格的方向。
我已经能够以NameValueCollection
获取数据,而这些数据并不像我希望的那样处理重复的列名。我本来喜欢一个字典,表名作为键,列的列为值;以下示例:
{"table_1": {"col_1": value, "col_2": value}, "table_2": {"col_1": value, "col_2": value}}
或者是合格的列名,以便我可以访问以下项目:
reader["table_name.column_name"];
我还能够从DataTable中获取查询中的数据,而DataTable不会以我想要的方式获取数据。上面示例中的id列只是附加一个数字1,表示它是重复的。
我用来返回NameValueCollections和DataTable的两个函数如下:
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;
}
}
非常感谢任何帮助! :)
答案 0 :(得分:2)
我认为问题出在您的SQL查询中。您必须为要从表中检索的每列设置名称。所以你可以使用这个查询:
SELECT table_1.ID as Tbl1_ID, table_2.ID as Tbl2_ID FROM table_1 JOIN table_2 ON table_1.id = table_2.id;
现在您可以通过它的名称读取每个列值,例如:
reader["Tbl1_ID"];
或它的索引,如:
reader[0];