首页 > 解决方案 > 应用程序登录系统不工作 SQL LOCAL

问题描述

我正在做我的程序,我需要登录和注册系统。我的注册系统正在运行,但无法登录。

我做了注册系统

SqlConnection sqlCon = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "'", sqlCon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows[0][0].ToString() == "1")
{
    SqlConnection sqlConn = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True");
    SqlDataAdapter sdaa = new SqlDataAdapter("Select Count(*) From UsersConfig where Email='" + textBox1.Text.Trim() + "' and Password='" + textBox2.Text.Trim() + "' and AdminYes='" + "1" + "'", sqlConn);
    DataTable dtbll = new DataTable();
    sdaa.Fill(dtbll);
    if (dtbll.Rows[0][0].ToString() == "1")
    {
        MessageBox.Show("Has admin");
        Form adminpanel = new AdminPanel();
        adminpanel.Show();
        this.Hide();
    }
    else
    {
        MessageBox.Show("Hasn't got admin");
    }
}
else
{
    MessageBox.Show("Not working!");
}

我没有错误信息

标签: c#sqlwinforms

解决方案


来自上述评论和 Microsoft 链接的建议会将代码更改为如下所示。此外,强烈建议使用参数而不是手动构建字符串,因为构建 SQL 字符串会导致 SQL 注入安全漏洞。

注意:我认为这不会解决您遇到的错误,但它可能有助于找到问题。

string connectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Initial Catalog = ConnectionDb; Integrated Security = True";

using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
    string email = textBox1.Text.Trim();
    string pwd = textBox2.Text.Trim();

    //NOTE: passwords shouldn't be stored in plain text. 
    //There should be an hashing step here like:
    pwd = MyCustomPasswordHasher(email, pwd);

    string sql = "Select [AdminYes] From UsersConfig where Email=@user and Password=@password";

    SqlCommand command = new SqlCommand(sql, sqlCon);
    command.Parameters.AddWithValue("@user", email);
    command.Parameters.AddWithValue("@password", pwd);

    try
    {
        command.Connection.Open();
        object result = command.ExecuteScalar();

        if (result == null)
        {
            MessageBox.Show("Invalid credentials!");
        }
        else if (result.ToString() == "1")
        {
            MessageBox.Show("Has admin");
            Form adminpanel = new AdminPanel();
            adminpanel.Show();
            this.Hide();
        }
        else
        {
            MessageBox.Show("Hasn't got admin");
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show("Database errors!");
    }
}

推荐阅读