我在尝试从mySQL获取数据时遇到错误:
Additional information: Could not find specified column in results: admin
我的代码是:
public int getLevel()
{
string sqlCommand = "Select level from users where username = 'admin'";
int value = 0;
MySqlConnection con = new MySqlConnection("host=111.222.111.222;user=MYUSERNAME;password=MYPASSWORD;database=tcg;");
MySqlCommand cmd = new MySqlCommand(sqlCommand, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader.GetString("admin"));
}
return value;
}
答案 0 :(得分:1)
尝试:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = @ad";
cmd.Parameters.AddWithValue("@ad","admin");
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader[0]);
}
}
con.Close();
}
return value;
}
如果您只有一个管理员,请使用:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = @ad";//add Order by if you need to
cmd.Parameters.AddWithValue("@ad","admin");
value += Convert.ToInt32(com.ExecuteScalar());//this assumes you will get an integer value
}
con.Close();
}
return value;
}