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();
4

2 回答 2

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());
        }
    }
}
于 2012-12-27T06:33:34.000 回答
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();
}
于 2012-12-27T07:06:19.043 回答