简体   繁体   中英

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
    {
    }
}

I'm quite just learning C# using vs. I am trying to connect the login button into the SQL I created. I can't run the program. it keeps giving me the error

SqlConnection does not contain a constructor that takes 3 arguments.

How do I solve it?

Your primary issue is that your connection string isn't right. It contains spurious ", which makes C# think you have three parameters. There are also other strange syntax errors.

There are other improvements:

  • On the first line, && should be || . You also need to bail out if the fields are not filled.
  • SqlCredential is unnecessary, but you may want to put the connection string in a settings file.
  • SqlDataAdapter and DataTable are only necessary if you want to use data-binding to your UI. Otherwise you can use ExecuteReader and loop it whil (reader.Read())
  • In this case, you don't even need that, because you only check for existence of a row. So you can just use cmd.ExecuteScalar
  • You need to pass the connection object to the command, and you need to open the connection.
  • You need to dispose the connection and command with using .
  • Always pass the exact parameter type, using SqlDbType , along with the length, precision or scale if relevant.
  • Never store plain-text passwords. Salt-and-hash them, and compare the hashes on the server. Do not retrieve the stored hash to the client app.
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);
    }
}
  • Consider using async and await to keep the UI alive.
private async void button1_Click(object sender, EventArgs e)
{
.....
            await conn.OpenAsync();
            var exists = ((await cmd.ExecuteScalarAsync()) as int) == 1;
            conn.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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