Skip to content

QueryTimeout

v-ahibr edited this page Feb 6, 2017 · 4 revisions

As of 6.1.1, the Microsoft JDBC Driver for SQL Server supports setting the query timeout via the connection string. This allows a default query timeout to be set for all queries on that connection. Below is an example of setting a default queryTimeout of 5 seconds using the connection URL.

String conURL = "jdbc:sqlserver://localhost;userName=sa;password=PASSW0RD;database=master;queryTimeout=5";
SQLServerConnection con = (SQLServerStatement) DriverManager.getConnection(conURL);

Another way to set the default queryTimeout is using a SQLServerDataSource object.

SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser("sa");  
ds.setPassword("PASSWORD");  
ds.setServerName("localhost");  
ds.setPortNumber(1433);   
ds.setDatabaseName("master");
ds.setQueryTimeout(5);
SQLServerConnection con = (SQLServerConnection) ds.getConnection();

After either of the above methods, all SQLServerStatement objects created using the connection con will be assigned a default queryTimeout of 5 seconds.

If needed, this default queryTimeout can be overridden. Below is an example of changing the queryTimeout property on a SQLServerStatement from the default 5, which was set above, to the value 2.

SQLServerStatement stmt = (SQLServerStatement) con.prepareStatement("SELECT * FROM table1");
stmt.setQueryTimeout(2);
Property Type Default Description
queryTimeout Int 0 The number of seconds to wait before a timeout has occurred on a query. The default value is 0, which means infinite timeout.
Clone this wiki locally