2013-11-28 12 views
5

Ora utilizzo il metodo in C# per leggere la tabella dal database SQLite in DataTable, ma voglio inviare tutta la tabella in un altro oggetto.Esiste un metodo semplice per leggere tutte le tabelle dal database SQLite all'oggetto DataSet?

Quindi penso di dover utilizzare DataSet per combinare tutti i DataTable (s) e inviarlo a oggetto come parametro.

Esiste un metodo per leggere facilmente tutte le tabelle dal database SQLite a DataSet? Oppure devo leggere tutte le tabelle dal database SQLite a DataTable ogni tabella e combinare a DataSet a mano?

+0

È possibile ottenere i nomi delle tabelle da qui: http: //stackoverflow.com/questions/4770716/reading-sqlite-table-information-in-c-net. Una volta ottenuti i nomi delle tabelle, è possibile creare un DataTable in base a ciascuno e aggiungerlo al set di dati. Tuttavia, il set di dati potrebbe essere ENORME. – NoChance

risposta

10

Lo sql messa in vendita di tutte le tabelle è:

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

si potrebbe quindi ottenere tutte le tabelle come database separatamente e poi aggiungerli in un set di dati - un esempio qui: http://www.dotnetperls.com/dataset

quindi credo che il codice sarebbe qualcosa di simile:

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

per getTable e GetDataTable (lascio il mettendo insieme a voi):

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; 
     } 
    } 
Problemi correlati