简体   繁体   English

如何使用SqlDataReader从数据库中检索信息,C#

[英]How to use SqlDataReader to retrieve information from database, c#

I need to access a variable in my SQL database, along with a username which is already implemented properly. 我需要访问SQL数据库中的变量以及已经正确实现的用户名。 I query the database using this statement: 我使用以下语句查询数据库:

private const string _getUserByUsernameQuery = @"
SELECT
    [User].[username]
FROM
    [User] WITH (NOLOCK) 
    INNER JOIN [Company] WITH (NOLOCK)
    ON [User].[companyId] = [Company].[id]
WHERE
    [User].[username] = @username 
    AND [User].[password] = @password";

Then connect to the database and access the username: 然后连接到数据库并访问用户名:

using (SqlConnection connection = new SqlConnection(SQLConfiguration.ConnectionString))
{
   SqlCommand command = new SqlCommand(_getUserByUsernameQuery, connection);
   command.Parameters.AddWithValue("@username", username);
   command.Parameters.AddWithValue("@password", password);
   try
   {
      connection.Open();
      using (SqlDataReader reader = command.ExecuteReader())
      {
         if (reader.Read())
         {
            Username = Convert.ToString(reader["username"]);
            //CompanyId = Convert.ToString(reader["companyId"]);
            lblUsername = Username;
            //lblCompanyId = CompanyId;
            Debug.WriteLine("Testing2::");
            Debug.WriteLine(lblUsername);
            //Debug.WriteLine(lblCompanyId);
         }
      }
   }
   catch (Exception)
   {
      if(connection.State == System.Data.ConnectionState.Open)
      connection.Close();
   }
}

In the if statement where I set reader["username"] equal to Username, I output Username using debug and the value is correct. 在将我的reader [“ username”]设置为Username的if语句中,我使用debug输出Username,并且该值正确。 What i have in comments relating to CompanyId is what I want to do, but was unable. 我在与CompanyId相关的评论中所要做的只是我想做的,但无法完成。 Doing so doesn't cause errors, but it does ignore the entire statement (even the Username variable which works otherwise). 这样做不会导致错误,但是会忽略整个语句(即使是Username变量也可以)。 based on my query string, how can I access the variable companyId? 根据我的查询字符串,如何访问变量companyId?

In your _getUserByUsernameQuery you are only selecting the username field. _getUserByUsernameQuery您仅选择username _getUserByUsernameQuery段。 Make sure that fields that you want to read from reader[...] are present in your select statement. 确保select语句中存在要从reader[...]读取的字段。

Looks like you need to add company id to your select statement to be able to retrieve it: 看来您需要在选择语句中添加公司ID才能进行检索:

private const string _getUserByUsernameQuery = @"
SELECT
    [User].[username], [User].[companyId]
FROM
    [User] WITH (NOLOCK) 
    INNER JOIN [Company] WITH (NOLOCK)
    ON [User].[companyId] = [Company].[id]
WHERE
    [User].[username] = @username 
    AND [User].[password] = @password";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM