1

I have a project and when I try to run it and the data test is big I have always a connection timeout. I added "sqlCmd.CommandTimeout = 3600;" but still not working. What could am I doing wrong?

This is my code:

public void createCode(String ce, int ord, String beh, int wkd)
{
        String strSql = "";
        SqlCommand sqlCmd;

        SqlConnection conexion = new SqlConnection(getConexion());

        try
        {
            if (conexion.State != ConnectionState.Open)
                conexion.Open();

            //The insert works fine in sql server
            strSql = "Insert into x with values"; 

            sqlCmd = new SqlCommand(strSql, conexion);
            sqlCmd.CommandTimeout = 3600;
            sqlCmd.ExecuteScalar();
        }
        catch (Exception ex)
        {               
            throw new Exception("Error creating Code. " + ex.Message);
        }
        finally
        {
            if (conexion.State == ConnectionState.Open)
                conexion.Close();
        }

}
1
  • Please, provide an error message and connection string (obfuscating its secret parts). It is important to distinct two different timeout types: ConnectionTimeout and CommandTimeout. Which timeout does cause error in your code? Commented Mar 27, 2020 at 10:18

2 Answers 2

1

You might need to set transaction timeout in your config file, like so;

<system.transactions>
   <defaultSettings timeout="01:00:00" />
</system.transactions>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! This was the problem! :)
Glad to help :)
0

sqlCmd.ExecuteScalar() is not correct for your script, try using sqlCmd.ExecuteNonQuery() instead and remove timeout.

        sqlCmd = new SqlCommand(strSql, conexion);
        sqlCmd.ExecuteNonQuery();

Check each function, ExecuteScalar tries to return first value from a select, while ExecuteNonQuery does not retrieve any value, just gets num of rows affected.

Hope it helps!

2 Comments

This is not the problem because I have been using this from years. But thank you David.
So if you are sure your script and sql is ok, you may use sqlCmd.CommandTimeout = 0 and it won't fail due to sql timeout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.