2013-06-24 23 views
2

如果表和列在sqlite中生成代碼後面是否有可能獲得列名(Header)?是否有可能使用C#獲取SQLite中的列名(標題)?

試過,但它失敗:

SQLiteCommand cmd = new SQLiteCommand(); 

string sSQL = "Select * from tblUser Where username = '" + txtUsername.Text + "'"; 
cmd.CommandText = sSQL; 
cmd.Connection = clsCon.con; 
SQLiteDataReader dr2; 
dr2 = cmd.ExecuteReader(); 
string columnName = dr2.GetName(1); 
dr2.Read(); 

if (dr2.HasRows) 
{ 
    MessageBox.Show("Username Already Exist!", "SQLite Test Application", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
    txtUsername.Focus(); 
} 
+4

** WARNING **:您的代碼很容易受到[SQL注入](http://en.wikipedia.org/wiki/SQL_Injection)攻擊。要清楚,你想要的行和列的名稱?它看起來並不像你在上面的代碼中檢索的那樣。 – Brian

+0

@Brian是的,我只想獲得每個列的名稱,我生成一個表。 – Jesson

+1

數據庫訪問代碼(當然在後面的代碼中),後面跟着'MessageBox'後面跟着'txtUsername.Focus();'。史詩。請花些時間,獲取一些關於編程的介紹教程。你的代碼幾乎違反了人類創造的每一種良好的習慣和模式。 –

回答

7

1)確保數據庫是開放

2)確保命令迷上了連接

3)確保你沒有得到任何錯誤

4)通過列名循環

var cmd = new SQLiteCommand("select * from t1", db); 
var dr = cmd.ExecuteReader(); 
for (var i = 0; i < dr.FieldCount; i++) 
{ 
    Console.WriteLine(dr.GetName(i)); 
} 
+0

這隻會得到一個想法列名。他想要他們。 – Brian

+6

@Brian:好吧,我可以展示如何編寫一個for循環,我猜。大聲笑。 – muratgu

1

基於由muratgu提供的答案,我創建了以下方法:

/// <summary> 
    /// Checks if the given table contains a column with the given name. 
    /// </summary> 
    /// <param name="tableName">The table in this database to check.</param> 
    /// <param name="columnName">The column in the given table to look for.</param> 
    /// <param name="connection">The SQLiteConnection for this database.</param> 
    /// <returns>True if the given table contains a column with the given name.</returns> 
    public static bool ColumnExists(string tableName, string columnName, SQLiteConnection connection) 
    { 
     var cmd = new SQLiteCommand("PRAGMA table_info(" + tableName + ")", connection); 
     var dr = cmd.ExecuteReader(); 
     while (dr.Read())//loop through the various columns and their info 
     { 
      var value = dr.GetValue(1);//column 1 from the result contains the column names 
      if (columnName.Equals(value)) 
      { 
       dr.Close(); 
       return true; 
      } 
     } 

     dr.Close(); 
     return false; 
    } 
相關問題