简体   繁体   中英

SQL Insert query, working all day but now fails everytime

What could cause the following error for the very first time when the exact same code (that produces this error) has been working perfectly all day today?


--------------------------- A 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)

--------------------------- OK

The code:

this.Cursor = Cursors.WaitCursor;
            try
            {
                // Insert into database
                sqlconnection = new SqlConnection(@"Data Source=" + Properties.Settings.Default.DBHost + ";Initial Catalog=BLAHBLAH;Persist Security Info=True;User ID=" + Properties.Settings.Default.DBUserName + ";Password=" + Properties.Settings.Default.DBPassword + ";");

                sqlconnection.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlconnection;

                int count = 0;

                foreach (var item in files)
                {
                    cmd.CommandText = @"insert into Images (Name, Games) values ('" + item.Value + "', '" + games + "')";
                    cmd.ExecuteNonQuery();

                    count++;
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            sqlconnection.Close();

            this.Cursor = Cursors.Default;

This is Sql server network connection error. try to login in sql browser also check your sql service is running or not and try to debug your code that are you able to open connection check/login credentials.

Firstly, I'd like to thank everyone for their help and suggestions. I've managed to solve this problem.

As it turns out, the reason this code was failing was because there was an issue with retrieving setting data from Properties.Settings.Default.SettingName. The settings are there and saved, but it wasn't able to retrieve the settings into variables for some reason.

I got this code to work by storing settings somewhere else other than Properties.Settings.

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