【问题标题】:Error while query a Textbox查询文本框时出错
【发布时间】:2012-12-27 06:30:26
【问题描述】:

这应该是一个简单的解决方案,但 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();

【问题讨论】:

  • 我认为你错过了 connection.open()
  • 你好像忘记打开连接了。

标签: c# mysql sql visual-studio


【解决方案1】:
  • 打开连接
  • 使用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());
        }
    }
}

【讨论】:

  • 这里没有任何错误,但是,Textbox1 说它在当前上下文中不存在。到目前为止,上面的代码似乎只在 Form_Load 函数中工作。对安置等有什么建议吗?
  • 代码可以独立运行。所以最好将它包装在一个方法中,并在每次需要在数据库中查询时调用该方法。引发的确切错误是什么?
  • 看起来大多数问题都已经解决了,错误现在会在以下位置吐出 SQL 语法错误: SELECT SUM(Dues Paid) From Students ;我对 SQL 比较陌生,但这似乎是正确的。
  • 这是您使用的查询SELECT SUM(Dues Paid) From Students吗?由于Dues Paid 列包含空格,因此应使用反引号将其包装起来,例如 SELECT SUM(`Dues Paid`) From Students
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2017-06-25
    相关资源
    最近更新 更多