如何将Sql数据转换为字符串变量或标签

时间:2018-03-07 10:40:09

标签: c# sql-server

如何从表中获取数据并将其转换为字符串。我正在尝试将 [用户级别] 转换为字符串变量或将其转换为标签。

我目前的代码是

private void btnLogin_Click(object sender, EventArgs e)
{
    if (attempt == 0)
    {
        lblMsg.Text = ("ALL 3 ATTEMPTS HAVE FAILED - CONTACT ADMIN");
        return;
    }

    scn.ConnectionString = @"Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True";            
    SqlCommand scmd = new SqlCommand("select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd", scn);            
    scmd.Parameters.Clear();
    scmd.Parameters.AddWithValue("@usr", txtUser.Text);
    scmd.Parameters.AddWithValue("@pwd", txtPass.Text);            
    scn.Open();

    if (scmd.ExecuteScalar().ToString() == "1")                
    {

        MessageBox.Show("You are granted with access.");
        this.Hide();
        frmMain frmmain = new frmMain();
        frmmain.Closed += (s, args) => this.Close();
        frmmain.Show();

    }
    else
    {
        MessageBox.Show("Invalid Username or Password.");
        lblMsg.Text = ("You have only " + Convert.ToString(attempt) + " attempt left to try.");
        --attempt;
        txtUser.Clear();
        txtPass.Clear();
    }
}

4 个答案:

答案 0 :(得分:0)

如果要同时读取计数和用户级别,可以使用SqlDataReader和ExecuteReader而不是ExecuteScalar()。我对您的SQL查询字符串稍作修改。运行此选项并查看变量以查看您返回的内容。

SqlCommand scmd = new SqlCommand("select count ([User Level]) as UserCount, [User Level] from tblUsers where [User Name]=@usr and Password=@pwd", scn);
scmd.Parameters.Clear();
scmd.Parameters.AddWithValue("@usr", txtUser.Text);
scmd.Parameters.AddWithValue("@pwd", txtPass.Text);            
scn.Open();

string userLabel = "";
int userCount = 0;
try
{
      SqlDataReader reader = cmd.ExecuteReader();
      if (reader.Read())
      {
        userLabel = (string)reader["User Level"];
        userCount = (int)reader["UserCount"];
      }
 }
 catch (Exception ex)
 {
      //do something here if it fails. 
 }

if (userCount == 1) 
{
     MessageBox.Show("You are granted with access.");
     //rest of your code....
}

也许您的查询不会像您期望的那样返回1个用户。尝试在数据库中运行查询以查看它返回的内容。如果是这种情况,则根据需要调整代码。

答案 1 :(得分:0)

如果想要从表中读取所有数据,请使用此代码。

    SqlCommand scmd = new SqlCommand("select * from tblUsers where [User Name]=@usr and Password=@pwd", scn);
    DataTable result = new DataTable();
    using (SqlDataReader reader = scmd.ExecuteReader())
    {
     result.Load(reader);
    }

然后你可以从表格列中读取数据。使用此代码

    result.Load(reader);          
    var userLevel=result[0]["User Level"]

答案 2 :(得分:0)

您的问题存在于您的SQL查询中。

select count ([User Level]) as count from tblUsers where [User Name]=@usr and Password=@pwd

您正在选择COUNT()而不是实际的[用户级别]。 COUNT()将始终返回一个数字,在这种情况下为1,如果存在提供的用户名和密码的用户(如果它具有PRIMARY KEY),则为0,否则为0。您应该尝试将查询更改为:

select [User Level] from tblUsers where [User Name]=@usr and Password=@pwd

然后你可以用

检查它的用户级别
string userLevel = scmd.ExecuteScalar();

如果userLevel == null,则用户名不存在(或者没有提供的密码)。请记住,如果数据库中[用户级别]的值为NULL,ExecuteScalar()将返回一个无法转换为String的DBNull,并且将失败。

答案 3 :(得分:0)

我更改了代码并以标签形式将字符串发送到mainform。我使用sqladapter而不是sqlcommand。

if (dt.Rows.Count == 1)
            {
                if (dt.Rows[0][0].ToString() == "Admin")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
                else if (dt.Rows[0][0].ToString() == "User")
                {
                    MessageBox.Show("You are granted with access.", "Welcome!");
                    this.Hide();
                    frmMain fma = new frmMain(dt.Rows[0][0].ToString());
                    fma.Closed += (s, args) => this.Close();
                    fma.Show();
                }
            }