while循环中返回

trnvg8h3  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(461)

我有一个c语言的方法,有一个数据库。现在我尝试返回值,但是因为字符串是在 while 它说它不存在。有没有办法 kampioen 在while read循环中创建的值是否可以返回?

public string getkampioen(string selecteditem)
{
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
        string query = ("select * FROM clubs where naam = '" + selecteditem + "'");
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read())
        {
           string kampioen = (string)Reader["aantalkampioenschappen"].ToString();
        }
        return kampioen; 
    }
}
bksxznpy

bksxznpy1#

只需将声明移到循环之外:

public string getkampioen(string selecteditem)
{
    string kampioen; //declare here
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
        string query = ("select * FROM clubs where naam = '" + selecteditem + "'");
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read())
        {
           kampioen = (string)Reader["aantalkampioenschappen"].ToString();
        }
        return kampioen; 
    }
}
q9yhzks0

q9yhzks02#

正如其他人所说,行动起来 kampioen 在圈外。但是,如果您希望获得一个特定值而不是随机值(如果返回多个记录),则可能需要连接字符串或将结果限制在第一行,如下所示:

public string getkampioen(string selecteditem)
{
    string kampioen = string.empty; // declared outside of the while 
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
        string query = ("select * FROM clubs where naam = '" + selecteditem + "' limit one");
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read())
        {
           kampioen = (string)Reader["aantalkampioenschappen"].ToString();
        }
        return kampioen; 
    }
}
2fjabf4q

2fjabf4q3#

可以在while循环之前声明字符串。

public string getkampioen(string selecteditem)
{
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
        string query = ("select * FROM clubs where naam = '" + selecteditem + "'");
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader Reader = cmd.ExecuteReader();
        string kampioen = "";
        while (Reader.Read())
        {
           kampioen = (string)Reader["aantalkampioenschappen"].ToString();
        }
        return kampioen; 
    }
}

相关问题