简体   繁体   中英

Error 1042 has occurred: Connect Timeout expired

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

在此处输入图像描述

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;

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