繁体   English   中英

如何在 C# 中将登录按钮连接到我的 SQL Server 数据库?

[英]How to connect the login button to my SQL Server database in C#?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using static System.Data.SqlClient.SqlConnection;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private SqlCommand cmd;

        private Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" && textBox2.Text == "")
            {
                MessageBox.Show("Please fill up all fields");
            }

            try
            {
                SqlCredential Librarypavilion = null;

                SqlConnection SqlConnection = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=", Librarypavilion, ";Integrated Security=True");

                SqlCommand; cmd = new SqlCommand("select * from login where username = @username and password = @password");
                cmd.Parameters.AddWithValue("@username", textBox1.Text);
                cmd.Parameters.AddWithValue("@password", textBox2.Text);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();

                da.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show(" User is successfully logged in");
                }
                else
                {
                    MessageBox.Show("Login unsuccessful");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex);
            }

            if (textBox2.Text == "")
            {
                MessageBox.Show("Please fill up password");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new WindowsFormsApp1.Form2();
            frm2.Show();
        }
    }

    internal class sqlConnection
    {
    }
}

我只是在使用 vs 学习 C#。我正在尝试将登录按钮连接到我创建的 SQL 中。 我无法运行程序。 它一直给我错误

SqlConnection 不包含采用 3 个参数的构造函数。

我该如何解决?

您的主要问题是您的连接字符串不正确。 它包含虚假",这使得C#认为你有三个参数。还有其他奇怪的语法错误。

还有其他改进:

  • 在第一行, &&应该是|| . 如果字段未填写,您还需要退出。
  • SqlCredential是不必要的,但您可能希望将连接字符串放在设置文件中。
  • 仅当您想对 UI 使用数据绑定时,才需要SqlDataAdapterDataTable 否则,您可以使用ExecuteReader并在whil (reader.Read())时循环它
  • 在这种情况下,您甚至不需要它,因为您只检查是否存在一行。 所以你可以只使用cmd.ExecuteScalar
  • 您需要将连接对象传递给命令,并且您需要打开连接。
  • 您需要using处理连接和命令。
  • 始终使用SqlDbType传递确切的参数类型,以及相关的长度、精度或比例。
  • 切勿存储纯文本密码。 对它们进行加盐和哈希处理,并比较服务器上的哈希值。 不要将存储的哈希检索到客户端应用程序。
private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox2.Text =="")
    {
        MessageBox.Show("Please fill up all fields");
        return;  //make sure to bail out
    }
    try
    {
        const string query = @"
select 1
from [login]
where username = @username
  and password = @password;
";
        using (var conn = new SqlConnection("Data Source=DESKTOP-90R7QPM;Initial Catalog=Librarypavilion;Integrated Security=True")
        using (var cmd = new SqlCommand(query, conn)
        {
            cmd.Parameters.Add("@username", SqlDbType.NVarChar, 255).Value = textBox1.Text;
            cmd.Parameters.Add("@password", SqlDbType.VarBinary, 128).Value = HashPassword(textBox1.Text, textBox2.Text);

            conn.Open();
            var exists = (cmd.ExecuteScalar() as int) == 1;
            conn.Close();
            if (exists)
            {
                MessageBox.Show(" User is Successfully login");
            }
            else
            {
                MessageBox.Show("unsuccessful");
            }
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
  • 考虑使用asyncawait来保持 UI 活跃。
private async void button1_Click(object sender, EventArgs e)
{
.....
            await conn.OpenAsync();
            var exists = ((await cmd.ExecuteScalarAsync()) as int) == 1;
            conn.Close();

暂无
暂无

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

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