我试图从数据库中获取单个值,但循环似乎根本没有开始?
if (connection.State == ConnectionState.Open)
{
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
value = dataReader["amount"].ToString();
}
dataReader.Close();
connection.Close();
}
这些是命令:
public string value;
public static string Konekcija = "Server=127.0.0.1; Database=CardIgrica; Uid=admin; Pwd=admin;";
public string komanda = "SELECT amount FROM CardIgrica.creaures WHERE id = '1';";
MySqlConnection connection = new MySqlConnection(Konekcija);
MySqlCommand cmd = new MySqlCommand(komanda, connection);
connection.Open();
答案 0 :(得分:0)
尝试选择
public string value {get; set;}
string komanda ="SELECT amount FROM CardIgrica.creaures WHERE id = 1";
答案 1 :(得分:0)
首先打开你的sql连接然后创建MySqlCommand的对象,如下所示:
MySqlConnection connection = new MySqlConnection(Konekcija);
connection.Open();
MySqlCommand cmd = new MySqlCommand(komanda, connection);
答案 2 :(得分:0)
试试这个
using (SqlConnection conn = new SqlConnection(Konekcija))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.CommandText = komanda ;
conn.Open();
var dataReader= cmd.ExecuteReader();
while (result.Read())
{
value = dataReader["amount"].ToString();
}
conn.Close();
}
答案 3 :(得分:0)
如果您需要单一值,则可以使用cmd.ExecuteScalar();
代替cmd.ExecuteReader();
因为ExecuteScalar()
将返回单个值。