我在C#中有一个带有数据库的方法。现在,我尝试返回该值,但是由于该字符串是在while
循环中创建的,因此表明该字符串不存在。是否可以返回在while读取循环中创建的字符串kampioen
及其值?
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;
}
}
答案 0 :(得分:1)
只需将声明移出循环:
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;
}
}
答案 1 :(得分:1)
您可以在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;
}
}
答案 2 :(得分:0)
正如其他人所说,将public class MainActivity extends AppCompatActivity {
ListView list;
ArrayList<Flick> flicks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = findViewById(R.id.list);
flicks = new ArrayList<>();
flicks.add(new Flick("Wizard of Oz", "Metro-Goldwyn-Mayer", "VARIOUS","1939", "", 98));
...
flicks.add(new Flick("Jaws", "Universal", "Steven Spielberg", "1975", "", 97));
CustomAdapter customAdapter = new CustomAdapter(this, R.layout.custom_layout, flicks);
listt.setAdapter(customAdapter);
}
...
}
移到循环之外。而且,如果您要获取一个特定值而不是一个随机值(如果返回了多个记录),则可能需要连接字符串或将结果限制为第一行,如下所示:
kampioen