首页 > 解决方案 > 我的 MySql 'SELECT' 命令有问题

问题描述

我想从我的表中获取第一个 id 并将其写入label16.text为我的程序创建页面。为什么以下代码返回 system.threading.tasks.unwrappromise'1[system.object]?

await sqlConnection.OpenAsync();               
SqlCommand command = new SqlCommand("SELECT Id from Recipes order by id asc limit 1", sqlConnection);
label16.Text = command.ExecuteScalarAsync().Result.ToString();

标签: c#winformsdatatablesmdf

解决方案


你应该改变

label16.Text = command.ExecuteScalarAsync().Result.ToString();

var t = await command.ExecuteScalarAsync();
label16.Text = t.Unwrap().ToString();

为了填写答案,我也会从评论中粘贴这个。

你必须做的另一件事是修复你的 SQL 查询,它应该是

SELECT TOP(1) Id from Recipes order by id asc

第三个问题

我会这样做

try 
{
    var id = int.Parse(label16.Text);
    sqlDataAdapter = new SqlDataAdapter($"SELECT * FROM Recipes WHERE Id = {id}", sqlConnection);
} catch { // error handling } 

推荐阅读