2013-10-29 51 views
2

嘗試下面的C#代碼來獲取所有表名在數據庫中, 但我得到一個錯誤消息說:如何用OleDb,C#執行SHOW語句?

「System.Data.OleDb.OleDbException(0x80040E14):無效的SQL語句; 預期「DELETE 」,‘插入’,‘過程’,‘選擇’,或‘更新’......」

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tbx_Source.Text + ";"); 
OleDbCommand cmd = new OleDbCommand("SHOW TABLES;", conn); 
OleDbDataReader reader; 

try 
{ 
    conn.Open(); 
    reader = cmd.ExecuteReader(); 
    if (reader.HasRows) 
    { 
     while (reader.Read()) 
     { 
      cbx_Tables.Items.Add(reader.GetValue(0).ToString()); 
     } 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.ToString()); 
} 

如何執行這種與OleDb的命令?

謝謝:)

回答

1

既然你想顯示在數據庫中所有表(即MDB),你可以嘗試

  DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); 

      DataTable userTables = null; 
      using (DbConnection connection = factory.CreateConnection()) 
      { 

       connection.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data 
       Source=C:\test\testfile.accdb;Jet OLEDB:Database Password=yourrPassword;"; 

       string[] restrictions = new string[4]; 
       restrictions[3] = "Table"; 

       connection.Open(); 

       // Get list of user tables 
       userTables = connection.GetSchema("Tables", restrictions); 


       foreach (DataRow item in userTables.Rows) // You can use simple 
                  //looping to retreive the table Name 
       { 



       } 
      } 

爲我工作

+0

謝謝,但是如何從此DataTable中讀取表的名稱? – bonell96

+0

請檢查我的更新答案 – Rohit

0

我認爲你不能。

SHOW不是data-manipulation-statement

數據操縱語言=

SELECT ... FROM ... WHERE ... 
INSERT INTO ... VALUES ... 
UPDATE ... SET ... WHERE ... 
DELETE FROM ... WHERE ... 

數據定義語言=

CREATE TABLE ... 
DROP TABLE ... ; 
ALTER TABLE ... ADD ... INTEGER; 
1

雖然凱爾的回答就是我會通過使用DataTable的喜歡,你可以使用OleDBDataReader你有在您的問題代碼通過使OleDbCommand命令文本

Select TABLE_NAME From INFORMATION_SCHEMA.TABLES