0

When I try to run the program it starts normal but when I input the correct answer and hit enter the error:

ErrorA network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error:40 - Could not open a connection to SQL Server)

Is there something wrong with my code below? If there are no errors what could I possibly do to fix it?

        if (txt1.Text == "A" && txt2.Text == "B" && txt3.Text == "C" && txt4.Text == "D" && txt5.Text == "E" && txt6.Text == "F" && txt7.Text == "G" && txt8.Text == "H")
        {
            var txt = new[] { txt1, txt2, txt3, txt4, txt5, txt6, txt7, txt8};
            for (int i = 0; i < 8; i++)
            {
                txt[i].Enabled = false;
            }
            SqlConnection conn = new SqlConnection("Server=localhost;Database=abcdefgh;uid=root");
            try
            {
                conn.Open();
                SqlCommand insert = new SqlCommand("INSERT INTO txt_abcdefgh (a_txt1, b_txt2, c_txt3, d_txt4, e_txt5, f_txt6, g_txt7, h_txt8) VALUES('" + txt1.Text + "','" + txt2.Text + "','" + txt3.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + ";)", conn);
                insert.ExecuteNonQuery();
                MessageBox.Show("");
                pnlEasy.Visible = true;
                Height = 476;
                Width = 336;
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message);
            }
        }
        else
        {
            MessageBox.Show("Wrong answer" + "\nTry Again");
        }
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
PlusUltra
  • 31
  • 8
  • The error of `The server was not found or was not accessible.` is usually correct. Either you don't have SQL Server installed locally, or the service is not running. – Joe Enos Sep 09 '16 at 15:44
  • 4
    **warning** your code is excessively vulnerable to sql injection attacks! – Daniel A. White Sep 09 '16 at 15:45
  • 1
    **Please refer to [Best Practices - Executing Sql Statements](http://stackoverflow.com/documentation/.net/3589/ado-net/14261/best-practices-executing-sql-statements)**. The code is vulnerable to sql injection attacks, errors if characters are included in the parameters like a `'` single quote, connections remaining open when an exception is thrown. – Igor Sep 09 '16 at 15:47
  • Change to `SqlConnection("Server=(local);Database=abcdefgh;user id=root;password=password")` – Alex Kudryashev Sep 09 '16 at 16:03

0 Answers0