Home > Back-end >  Error 1042 has occurred: Connect Timeout expired
Error 1042 has occurred: Connect Timeout expired

Time:12-09

I am trying to connect to the SQL server with the below connection string but it is giving this "error Connect Timeout expired"

I have tried to telnet and it connected successfully. However, from the code, I cannot connect even though I have tried to specify the default port.

Is there anything am doing wrong? Thank you in advance.

            string _connectionString = @"Server=myIP,1433;Database=myDB;User Id=myID;Password=myPass;";
            using (MySqlConnection con = new MySqlConnection(_connectionString))
            {
                con.Open();
                string sqlQuery = "SELECT * FROM Inventory";
                using (MySqlCommand cmd = new MySqlCommand(sqlQuery, con))
                {
                    MySqlDataReader result = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    while (result.Read())
                    {
                        
                    }
                    con.Close();
                }
            }

Telnet result

enter image description here

CodePudding user response:

Use backslash if you have an instance of your SQL Server "Server=myIP\sqlexpress".

If the server is your local machine, use Windows Authentication instead:

"Server= localhost; Database= myDB; Integrated Security=True;"

Or you can use App.Config to configure your SQL connection`, this is how I configure mine using Windows Authentication, not username and password. First, add an App.config to your application. Then add this:

<connectionStrings>  
 <add name="SqlConnectionString" connectionString="Data Source=localhost;Initial Catalog=myDB;Integrated Security=true"/>  
</connectionStrings>

And on your program:

string _connectionString = string connString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;

using (con = new SqlConnection(_connectionString))
        {                
            string sqlQuery = "SELECT * FROM Inventory";
            SqlCommand cmd = new SqlCommand(sqlQuery, con)
            con.Open();
                SqlDataReader result = cmd.ExecuteReader();
                while (result.Read())
                {
                    
                }
                con.Close();
        }

Don't forget to add using directive:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
  • Related