2013-11-28 33 views
5

现在我使用C#中的方法将SQLite数据库中的表读入DataTable中,但我想将所有表发送到其他对象中。是否有简单的方法来读取SQLite数据库中的所有表到DataSet对象?

所以我想我必须使用DataSet来组合所有的DataTable(s) 并将它作为参数发送给对象。

是否有方法可以轻松地将所有表从SQLite数据库读取到DataSet? 或者我必须从SQLite数据库中读取所有表格到DataTable的每个表格 并手动合并到DataSet中?

+0

您可以从这里获取表名:http://stackoverflow.com/questions/4770716/reading-sqlite-table-information-in-c-net。一旦你有表名,你可以创建一个基于每个数据表并将其添加到您的数据集 - 但是,数据集可能会很大。 – NoChance

回答

10

上市的所有表的SQL是:

SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY 1 

,那么你可以得到所有的表作为seperately数据库,然后将它们添加到数据集 - 在这里一个例子:http://www.dotnetperls.com/dataset

,所以我猜代码将是这样的:

Dataset d = new Dataset() 
foreach (tableName in GetTables()){ 
    d.Tables.Add(GetDataTable("select * from "+tableName); 
} 

代码的getTables和GetDataTable(我会一起离开的拼凑它给你):

public ArrayList GetTables() 
    { 
     ArrayList list = new ArrayList(); 

     // executes query that select names of all tables in master table of the database 
      String query = "SELECT name FROM sqlite_master " + 
        "WHERE type = 'table'" + 
        "ORDER BY 1"; 
     try 
     { 

      DataTable table = GetDataTable(query); 

      // Return all table names in the ArrayList 

      foreach (DataRow row in table.Rows) 
      { 
       list.Add(row.ItemArray[0].ToString()); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.Message); 
     } 
     return list; 
    } 

    public DataTable GetDataTable(string sql) 
    { 
     try 
     { 
      DataTable dt = new DataTable(); 
      using (var c = new SQLiteConnection(dbConnection)) 
      { 
       c.Open(); 
       using (SQLiteCommand cmd = new SQLiteCommand(sql, c)) 
       { 
        using (SQLiteDataReader rdr = cmd.ExecuteReader()) 
        { 
         dt.Load(rdr); 
         return dt; 
        } 
       } 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.Message); 
      return null; 
     } 
    } 
相关问题