2013-01-10 47 views
1

如何獲得包含在MySQL數據庫中的所有表名的List<string>如何從MySQL數據庫中獲取表名的列表<string>?

我想加載一個完整的數據庫到一個DataSet中,但從我的理解看來,MySqlDataAdapter.Fill()只能在單個表上運行,對嗎?這就是我想要使用表字符串集合。

編輯:

  1. 我尋找正確的查詢:下面的回報,儘管數據庫59名不同的項目僅持有3個表:

    MySqlCommand command = new MySqlCommand("SELECT table_name FROM information_schema.tables where table_type = 'BASE TABLE'", connection); 
        var result = command.ExecuteReader(); 
    
  2. 我期待已久的C#代碼來解析查詢結果轉化爲List<string>

+0

如果全分貝一次被查詢,它將會出現內存不足 –

+0

@ArunKillu,爲什麼是這種情況。它完全取決於其內容。我有一個數據庫設置與幾個設置/屬性表,在應用程序啓動時加載。 –

回答

4

使用實體fraemwork,你的架構添加到的DbContext那麼你可以做這樣的:

var tableNames = context.MetadataWorkspace.GetItems(DataSpace.SSpace) 
         .Select(t => t.Name) 
         .ToList(); 

編輯:

Alternativly你可以使用普通的SQL查詢讀取tablen名稱(例如使用Show tables)並將它們解析成如下列表:

List<String> Tablenames = new List<String>(); 

using(SqlConnection connection = new SqlConnection("conn_string")) 
{ 
    string query = "show tables from YourDB"; 
    SqlCommand command = new SqlCommand(query, connection); 
    using (SqlDataReader reader = command.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      Tablenames.Add(reader.GetString(0)); 
     }   
    } 
} 
+0

對不起,但我喜歡沒有實體框架。但是,謝謝你的建議。 –

+0

然後您將不得不使用普通的sql查詢並將結果解析到列表中。 – CloudyMarble

+0

我的問題的全部點正是如何解析結果到列表:-)(請參閱我的第二點) –

1
  • 首先下載並安裝Connector/Net.這是在C#中使用MySQL所必需的。 MySQL for Visual Studio不是必需的,但我建議您安裝它。它可以幫助您在Visual Studio中設計MySQL數據庫。

  • 添加參考MySql.Data

  • 在你的代碼添加using MySql.Data.MySqlClient;

聲明這樣的功能:

public List<string> MySqlCollectionQuery(MySqlConnection connection, string cmd) 
{ 
    List<string> QueryResult = new List<string>(); 
    MySqlCommand cmdName = new MySqlCommand(cmd, connection); 
    MySqlDataReader reader = cmdName.ExecuteReader(); 
    while (reader.Read()) 
    { 
     QueryResult.Add(reader.GetString(0)); 
    } 
    reader.Close(); 
    return QueryResult; 
} 

然後創建一個MySQL連接,並調用這個函數:

string connStr = string.Format("user={0};password={1};database={2}", 
           username,password,database); 
List<string>TableNames = new List<string>();//Stores table names in List<string> form 
using(MySqlConnection Conn = new MySqlConnection(connStr)) 
{ 
    Conn.Open(); 
    string cmdStr = "show tables"; 
    TableNames = MySqlCollectionQuery(Conn,cmdStr); 
} 

我沒有把這個在try ... catch塊,但這樣做總是一個很好的做法。

相關問題