Created a login form with a local SQL database, after executing it and after trying to login, an "ArgumentException Unhandled" error occurred

I understand that the same was asked before and closed due to a simple typo. From what I can see, I don't have any typos and I tried to figure out the problem using Googling, but no luck.

I created this login window. Main login window

I created a local SQL database from Visual Studio (2015) to store my users. To establish a connection to this database, I wrote this line of code in my Enter button that is visible in the main login window.

SqlConnection sqlConn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C: \USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");

      

This path was inserted by right clicking my database and selecting properties. There is a field in the properties named Connection String. This is what I copied and pasted into the above path in the code.

This is all my code.

        //Find path for SQL Connection
        SqlConnection sqlConn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS();\SAFE BOX\DATABASE\SAFEBOXDB.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
        //Add query for actions to be taken once connection is established, select the user
        string sqlQuery = "Select * from dbo.Table Where username = '" + txtEnterUserName.Text.Trim() + "' and password = '" + txtEnterPassword.Text.Trim();
        //Add SQL Data Adapter passing in the connection and the query
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlQuery, sqlConn);

        //Create new Datatable object
        DataTable dataTable = new DataTable();
        //Fill SQL Data Adapter with the dataTable
        sqlDataAdapter.Fill(dataTable);

        if (dataTable.Rows.Count == 1)
        {
            loginMain objFormMain = new loginMain();
            this.Hide();
            UserDashboard userDash = new UserDashboard();
            userDash.Show();
        }
        else
        {
            MessageBox.Show("Check Username and Password");
        }

      

When I run the program, my main login window appears as the main window, I enter my credentials according to the table in the database, and I get this error as soon as I hit the Enter button.

ArgumentException error

I have checked and rechecked the path, but I cannot get it to work and I have no idea what the problem is. General google searches didn't help.

Due to low reputation, since I am a new user, I cannot load table data, I only have one row with username and password. Let's assume they are typed correctly.

The error indicates that the keyword is not supported. I don't seem to understand this.

EDIT. I have reinstalled the server and the new path is now

using (SqlConnection sqlConn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))

      

according to the new connection string. So the new code for the "Enter" button is now

private void enterButton_Click(object sender, EventArgs e)
    {
        string sqlQuery = @"Select * from dbo.Table 
                Where username = @user AND 
                      password = @pass";
        using (SqlConnection sqlConn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Nikos\Documents\SafeBox.mdf;Integrated Security=True;Connect Timeout=30"))
        using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
        {
            sqlConn.Open();
            cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
            cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    loginMain objFormMain = new loginMain();
                    this.Hide();
                    UserDashboard userDash = new UserDashboard();
                    userDash.Show();
                }
                else
                {
                    MessageBox.Show("Check Username and Password");
                }
            }
        }
    }

      

The new error I have is {"Incorrect syntax next to the 'Table' keyword." } and the error points to this line.

using (SqlDataReader reader = cmd.ExecuteReader())

      

+3


source to share


1 answer


There are many bugs in the code.

The first is the space between the C: drive letter and the remaining path is invalid and must be removed. Also, adding a semicolon in the middle of the connection string as part of the path confuses the connection parser, which uses a semicolon as the separator between keys and values. This is the source of the error message because after NIKOS (); semicolon, the parser ends up with its path detection and tries to make sense of the \ SAFE BOX .... since that was the key to parsing.
You have to remove it from your disk path and set up your connection string

SqlConnection sqlConn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;
      Initial Catalog=C:\USERS\NIKOS\DESKTOP\NIKOS\SAFE BOX\DATABASE\SAFEBOXDB.MDF;
       Integrated Security=True;
       Connect Timeout=30;
       Encrypt=False;
       TrustServerCertificate=True;
       ApplicationIntent=ReadWrite;
       MultiSubnetFailover=False");

      

Now the problems with the code are even worse



string sqlQuery = @"Select * from [Table] 
                    Where username = @user AND 
                          password = @pass";
using(SqlConnection sqlConn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
     sqlConn.Open();
     cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = txtEnterUserName.Text.Trim();
     cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = txtEnterPassword.Text.Trim();

     using(SqlDataReader reader = cmd.ExecuteReader())
     {
         if(reader.HasRows)
         {
              loginMain objFormMain = new loginMain();
              this.Hide();
              UserDashboard userDash = new UserDashboard();
              userDash.Show();
         }
         else
         {
              MessageBox.Show("Check Username and Password");
         }
    }
}

      

First of all, you don't need a complicated SqlDataAdapter if you just want to check if a user exists or not. A simple SqlCommand with a SqlDataReader will work fine.
Second, all disposable objects must be inside a using statement to make sure that when you finish using them, they will be destroyed in case of exceptions as well.

Finally, parameters always come when you need to pass values ​​to your database. Failure to use them will lead to Sql Injection attacks or unexpected syntax errors when your strings contain single quotes.

+3


source







All Articles