CommandTimeout

sqlCom.CommandTimeout = 60;

What It Means

CommandTimeout: command‑execution timeout, measured in seconds

  • Default value: 30 seconds
  • Here set to 60 → if the SQL statement does not finish within 60 seconds, a timeout exception gets thrown
    Make sure you tell these two timeouts apart
  1. ConnectionTimeout: configured inside the connection string, timeout for establishing the database connection
  2. CommandTimeout: takes effect after connection succeeds, wait‑timeout for running SQL statements

Full Working Example

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=.;Initial Catalog=db;User ID=sa;pwd=xxx";
    // using automatically disposes the SqlConnection resource
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlCommand sqlCom = new SqlCommand();
        // Bind connection (pick either syntax)
        sqlCom.Connection = conn;

        sqlCom.CommandText = "select 1";
        // Set SQL execution timeout to 60 seconds
        sqlCom.CommandTimeout = 60;

        object obj = sqlCom.ExecuteScalar();
        MessageBox.Show(obj.ToString());
    }
    // At the end of using block, conn closes and releases automatically, no manual conn.Close() needed
}Code language: JavaScript (javascript)

Important Notes

  1. Negative values are invalid. Zero means wait indefinitely (not recommended, your app may hang)
  2. Only applies to this particular SqlCommand instance; it is not a global setting
  3. Raise this value when stored procedures run very slowly.
    Always try optimizing your SQL first instead of just bumping the timeout endlessly.

Concise Object‑Initializer Style

SqlCommand sqlCom = new SqlCommand("select 1", conn)
{
    CommandTimeout = 60
};Code language: JavaScript (javascript)

Connection Timeout Configuration

Defined in connection string, completely independent from CommandTimeout:

Data Source=.;Initial Catalog=db;User ID=sa;Password=xxx;Connect Timeout=15

Connect Timeout=15 → maximum 15‑second wait while trying to connect to database.

CommandTimeout

Leave a Reply

Your email address will not be published. Required fields are marked *