如何从数据表中获取数据并将其放入C#中的变量中?

时间:2019-05-12 18:40:40

标签: c# sql dapper

我这里有一个简单的Login应用程序。我希望它获取给定用户名的ID,然后查看相同ID的密码是否匹配,以了解是否应授予用户访问权限。当我从表中获取信息时,它会包含很多我不需要的其他信息。如何将其优化为表格中的值? (在此示例中,仅字符串'

string id;
        string login;
        string password;

        string con = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\UserInfo.mdf;Integrated Security=True";
        //Connect to DB
        using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(con))
        {
            //Get ID
            id = connection.Query<string>($"select id from Users where Name = '{txtUsername.Text}'").ToString();
            MessageBox.Show(id);
        }

运行此命令时,我希望消息框显示“ 1”,但显示“ System.Collections.Generic.List'1 [System.String]”。

1 个答案:

答案 0 :(得分:1)

由于Dapper Query方法返回的是IEnumerable而不是单个值,所以会出现错误

  id = connection.Query<string>($"select id from Users where Name = '{txtUsername.Text}'").First();

id = connection.Query<string>($"select id from Users where Name = '{txtUsername.Text}'").Single();

尝试