从数据库中获取一个数据单元格

get one cell of data from database

我想从我的数据库中获取数据。 table 名称为MsUser,包含用户ID、用户名和密码。 有好几行。

表格说明: 我有登录,需要用户名和密码才能登录。 登录后打开交易表单,在该表单中将使用标签显示用户 ID,用户 ID 基于已登录的用户名。

这是我用来匹配用户名和密码的代码 对不起,如果我的英语不好。 非常感谢你的帮助,真的。

  private void btnLogin_Click(object sender, EventArgs e)
    {

        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True");

        SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From MsUser where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"'",cn);

        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows[0][0].ToString()=="1")
            {
                this.Hide();

            }
        else
        {
            MessageBox.Show("your id or password is wrong");
        }

    }

如果您恰好返回一行、一列(如 SELECT COUNT(*)),请使用 SqlCommand 及其 .ExecuteScalar() 方法 - 无需为单个数据表承担所有开销值!

使用这样的东西:

private void btnLogin_Click(object sender, EventArgs e)
{
    // define query - and **ALWAYS** use parameters!
    string query = "SELECT COUNT(*) FROM dbo.MsUser WHERE username = @UserName AND password = @password);";

    // set up connection and command
    using (SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True"))
    using (SqlCommand cmd = new SqlCommand(query, cn))
    {
        // define parameters and provide values
        cmd.Parameters.Add("@username", SqlDbType.VarChar, 100).Value = txtUserName.Text;
        cmd.Parameters.Add("@password", SqlDbType.VarChar, 100).Value = txtPassword.Text;

        // open connection, execute command, close connection
        cn.Open();
        var result = cmd.ExecuteScalar();
        cn.Close();

        // if result is not null and can be converted to an int....
        if(result != null)
        {
            int userCount;

            if(int.TryParse(result.ToString(), out userCount))
            {
                // OK, you have a good value - if it's > 0, your user entry exists....
                if (userCount > 0)
                {
                    // success - user exists with password
                }
                else 
                {
                    // no success - no such entry
                }
            }
            else
            {
               // you didn't get a numeric value......
            }
        }
        else
        {
            // you didn't get any value......
        }
    }
}

另外:请确保您永远不会将密码存储在纯文本中你的数据库 table !!

更新: 如果您需要检索 UserId(而不仅仅是计数),请使用如下查询:

string query = "SELECT UserId FROM dbo.MsUser WHERE username = @UserName AND password = @password);";

然后检查您是否取回了有效的 UserId(不确定可能是什么数据类型....)

var result = cmd.ExecuteScalar();

// checking if we got something (or null)
if (result != null)
{
    string userId = result.ToString();
}
else
{
     // we didn't get any "UserId" back -> invalid combination of "username" and "password"
}

这可能对您有所帮助,但请注意 Sql injection
更新代码以防止Sql注入。

private void btnLogin_Click(object sender, EventArgs e)
{
        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True");

        SqlCommand cmd1 = new SqlCommand("Select Count(*) From MsUser where username = @username and password = @passowrd", cn);
        cmd1.Parameters.AddWithValue("@username", idBox.Text.Trim());
        cmd1.Parameters.AddWithValue("@passowrd", passwordBox.Text.Trim());            

        int returnValue = Convert.ToInt32(cmd1.ExecuteScalar());

        if (returnValue == 1)
        {
             this.Hide();
        }
        else
        {
            MessageBox.Show("your id or password is wrong");
        }
 }

假设您的用户 table 包含每个用户名-密码组合的唯一记录,

private void btnLogin_Click(object sender, EventArgs e)
    {
        string requiredUserId;

        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\ProgII Project\MoneyManager\MoneyManager\MsUser.mdf;Integrated Security=True;User Instance=True");

        SqlDataAdapter sda = new SqlDataAdapter("Select Count(userID),UserId From MsUser where username='"+txtUsername.Text+"' and password='"+txtPassword.Text+"' Group By userID",cn);

        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows[0][0].ToString()=="1")
            {
                this.Hide();
                requiredUserId=dt.Rows[0][1].ToString(); //Use this requiredUserId in your next form!!
            }
        else
        {
            MessageBox.Show("your id or password is wrong");
        }

    }