0

我不想发布这个,但我找不到解决这个问题的答案。

我为朋友制作了一个应用程序,但是当我运行它时,它给了我一个警告,并且最近开始崩溃。

我尝试调试问题,它给了我一个完全不同的问题。

class DBApplication : DBInfo
{
    private MySqlConnection connection = new MySqlConnection();
    private int customer_id;
    public string lastname;

    //constructor
    public DBApplication()
    {
        OrderID();
    }

    public string OrderID()
    {
        customer_id = 8;
        //add the DataBase query to the string.
        string query = "SELECT * FROM wdb_customer WHERE=" + customer_id;

        if (OpenConnection() == true)
        {
            MySqlCommand myComm = connection.CreateCommand();
            MySqlDataReader Reader;
            myComm.CommandText = query;
            /*when I debugged, it said this was the problem? 
              but i dont understand why.*/*
            Reader = myComm.ExecuteReader(); 

            while (Reader.Read())
            {
                lastname = Reader["customer_name"].ToString();
            }
            Reader.Close();
        }
        return lastname;
    }
}

第一个问题“变量 DB_App 要么未声明,要么从未分配。”

这就是这个脚本。

partial class Form1 {
    ...
    private DBApplication DB_App = new DBApplication();
    ...
    private void InitializeComponent()
    {
       this.OrderID.Text = DB_App.lastname;
    }

我也试过 DB_App.OrderID(); 同样的问题。

4

1 回答 1

3

WHERE您的查询无效,因为您错过了子句中的列名

应用快速修复更改

string query = "SELECT * FROM wdb_customer WHERE=" + customer_id;

string query = "SELECT * FROM wdb_customer WHERE customer_id = " + customer_id;
                                                 ^^^ use real column name here

附带说明:不要直接从用户输入构建 SQL 查询字符串;改用参数。它可以防止您的代码被 SQL 注入在这里阅读更多

话虽这么说,您的代码可能看起来像这样

...
myComm.CommandText = "SELECT * FROM wdb_customer WHERE customer_id = @customer_id";
myComm.Parameters.AddWithValue("@customer_id", customer_id);
Reader = myComm.ExecuteReader(); 
...
于 2013-05-14T02:53:36.593 回答