首页 > 解决方案 > 检查数据是否存在后如何从数据库中获取数据

问题描述

我正在设置一个登录表单,其中包含 2 个用户,即“admin”和“user”。如果用户存在于数据库中,我需要在提供用户名和密码后获取用户类型。我有 2 个用于用户名和密码的文本框(用于输入)和另一个用于用户类型的文本框(查看什么用户类型)。从数据库中检查用户名和密码时,如何显示用户类型?请帮忙。谢谢你。

private void button3_Click(object sender, EventArgs e)
        {
            string query = "select * from [USER] where username= '" + Unametb.Text + "' and userpw='" + Pwordtb.Text + "'";
            using (SqlConnection xcon = new SqlConnection(@"Server=KINGARTHUR\SQLEXPRESS;Database=CENTER;Integrated Security=SSPI;"))
            {
                using (SqlCommand xcom = new SqlCommand(query, xcon))
                {
                    SqlDataReader xreader;
                    try
                    {
                        if (Unametb.Text.Equals("") && Pwordtb.Text.Equals(""))
                        {
                            MessageBox.Show("Username & Password is Empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (Unametb.Text.Equals(""))
                        {
                            MessageBox.Show("Username is Empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else if (Pwordtb.Text.Equals(""))
                        {
                            MessageBox.Show("Password is Empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            xcon.Open();
                            xreader = xcom.ExecuteReader();
                            int count = 0;

                            while (xreader.Read())
                            {
                                count = count + 1;
                            }
                            if (count == 1)
                            {
                                textBox1.Text = xreader.GetValue(3).ToString();
                                Form b = new Form();
                                b.Show();
                                this.Hide();
                            }
                            else
                            {
                                MessageBox.Show("Username or Password do not match!");
                            }
                            loginuser.user = Unametb.Text;
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        xcon.Close();
                    }

                }
            }
        }

标签: c#sql

解决方案


推荐阅读