【发布时间】:2015-08-26 15:36:15
【问题描述】:
我正在使用System.Data.SQLite。我正在编写一个从任何给定 SQLite 数据库读取数据的 C# 程序。
该程序在给定的数据库上运行许多查询。我查询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 中的查询中获取数据,它无法以我希望的方式获取数据。上面示例中的 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;
}
}
非常感谢任何帮助! :)
【问题讨论】:
标签: c# sqlite system.data.sqlite