Search code examples
sqlsql-serverlocaldbunhandled-exception

LogIn form, SQL exception


I'm trying to make a simple program that has a log-in part, with a local database just for testing.And i keep getting an error when I try to open the connection to the SQL database.

 private void logInButton_Click(object sender, EventArgs e)
    {
        MainMenu openMainMenu = new MainMenu();
        SqlConnection sqlcon = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30");
        sqlcon.Open();
        SqlCommand cmd = new SqlCommand("Select * from Table Where username ='" + usernameTextBox.Text + "' and password = '" + passwrodTextBox.Text + "'");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dtbl = new DataTable();
        sda.Fill(dtbl);
        if (dtbl.Rows.Count > 0)
        {
            openMainMenu.Show();
            this.Hide();
        }
        else
            MessageBox.Show("Wrong username or password!");
    }

I get the error at sqlcon.Open();, and it is: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: An attempt to attach an auto-named database for file C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."


Solution

  • Well, the best advice I can give you is to google the error message. Keep in mind that if there is an error message it means that the problem is well known an as such it's a safe bet that someone have encountered it before you and managed to solve it. The first 4 results of this search are on stackoverflow and at least two of them have accepted answers, so I believe a little reasearch would have saved you a long time.
    This is the best advice because it streaches far beyond your current problem. I firmly believe that good searching skills is the most important and most powerfull tools of a sotfware developer. I can assure you, no matter how much time you are developing software, almost every exception you get, someone else have already solved and posted the solution somewhere, you only need to find it.

    Now, as for the code it self - You have some major problems other then the exception you are asking about:

    1. Concatenating strings into sql statements instead of using parameters expose your code to SQL injection attacks. This is a very serious threat that is extremely easy to fix.
    2. Using insntances of classes that implements the IDisposable interface without properly disposing them may lead to memory leak. Read about the using statement and make it a habit to use it every time it's possible.
    3. Exception handling. Currently, if your database can't be reached, you get an exception and your program crash. You should use a try...catch block anywhere you can't control in code to let your program end gracefuly instead. (Don't ever use try...catch for things you can do in code such as validate user input or checking division by zero - only for things that are beyon your control such as database availability.)

    Having said all that, your code should look something like this:

    private void logInButton_Click(object sender, EventArgs e)
    {
        using (var sqlcon = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|C:\Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30"))
        {
            sqlcon.Open();
            using (var cmd = new SqlCommand("Select 1 from Table Where username = @userName and password = @password"))
            {
                cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = usernameTextBox.Text;
                cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = passwrodTextBox.Text;
                using (var dtbl = new DataTable())
                {
                    using (var sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(dtbl);
                    }
    
                    if (dtbl.Rows.Count > 0)
                    {
                        var openMainMenu = new MainMenu();
                        openMainMenu.Show();
                        this.Hide();
                    }
                }
                else
                {
                    MessageBox.Show("Wrong username or password!");
                }
            }
        }