2012-12-27 13 views
2

這應該是一個簡單的解決方案,但Visual Studio 2012給我的錯誤說,sqlCon是一個字段,但用於像TextBox1類型和相同的錯誤...也許我缺少一個程序集引用或正確的連接導入?我期待着繼續這個簡單的路線。查詢文本框時出錯

MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;"); 
    MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students"); 
     sqlCon.CommandText = "SELECT * count(Dues) FROM Students"; 
     sqlCon.Connection = sqlCon; 
     TextBox1.Text = sqlCon.ExecuteScalar().ToString(); 
+2

我想你已經錯過connection.open() – SRIRAM

+1

看來你忘了打開連接。 –

回答

4
  • 打開連接
  • 使用using語句
  • 使用Try-catch

片段,

string connStr = "Server=***;Port=***;Database=***;Uid=***;Pwd=***;"; 
string query = "SELECT count(Dues) From Students"; 
using(MySqlConnection sqlCon = new MySqlConnection(connStr)) 
{ 
    using(MySqlCommand sqlComm = new MySqlCommand()) 
    { 
     sqlComm.Connection = sqlCon; 
     sqlComm.CommandText = query; 

     try 
     { 
      sqlCon.Open(); 
      TextBox1.Text = sqlComm.ExecuteScalar().ToString(); 
     } 
     catch(MySqlException ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 
} 
+0

這裏沒有任何錯誤,但是,Textbox1表示它在當前上下文中不存在。到目前爲止,上述代碼似乎只能在Form_Load函數中使用。任何關於安置等的建議? – Klinetel

+0

該代碼可以自行工作。所以最好將它包裝在一個方法中,並在每次需要在數據庫中查詢時調用該方法。什麼是精確的錯誤? –

+0

它看起來像大多數問題已經解決,錯誤現在吐出SQL語法錯誤:SELECT SUM(Dues Paid)From Students;我在SQL方面比較新,但這看起來是正確的。 – Klinetel

1

MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;"); 
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students"); 

//sqlCon is of type MySqlConnection which is derived from DbConnection 
sqlCon.CommandText = "SELECT * count(Dues) FROM Students"; 

//sqlCon has no Connection property, and why are you even assigning sqlCon to that property 
sqlCon.Connection = sqlCon; 

//ofcourse this will fail 
TextBox1.Text = sqlCon.ExecuteScalar().ToString(); 

我相信你想達到什麼是:

MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;"); 
MySqlCommand command = new MySqlCommand ("SELECT count(Dues) From Students"); 

try 
{ 
    sqlCon.Open(); 
    command.Connection = sqlCon; 
    TextBox1.Text = command.ExecuteScalar().ToString(); 
} 
finally 
{ 
    sqlCon.Close(); 
}