Skip to content

Instantly share code, notes, and snippets.

@joelcarranza
Created December 19, 2012 19:57
Show Gist options
  • Save joelcarranza/4339931 to your computer and use it in GitHub Desktop.
Save joelcarranza/4339931 to your computer and use it in GitHub Desktop.
package org.sqlite;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Example of invoking Statement.cancel() on long running query. If the query is expensive and blocks for a significant
* time in executeQuery(), then Statement.cancel() fails to work correctly.
*/
public class SqliteCancelTest {
static PreparedStatement stmt;
static Connection conn;
static class RunQuery implements Runnable {
String sql;
public RunQuery(String sql) {
super();
this.sql = sql;
}
public void run() {
try {
System.out.println("RUNNING: " + sql);
stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
System.out.println("executeQuery() complete");
while (resultSet.next()) {
String value = resultSet.getString(1);
}
System.out.println("Completed");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
System.err.println("Statement.close() failed with: "
+ e);
}
}
try {
conn.close();
} catch (SQLException e) {
System.err.println("Connection.close() failed with: " + e);
}
}
}
}
public static void main(String[] args) throws Exception {
// arguments are <sqlite-file> <query>
// query should be an expensive query which takes a while to compute any results
// i typically use SELECT * FROM TABLE ORDER BY COLUMN where on a table with alot of
// rows and where COLUMN is non-indexed
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + args[0]);
new Thread(new RunQuery(args[1])).start();
// Query is running in separate thread, invoke cancel on statement
try {
while (stmt == null) {
Thread.sleep(100);
}
System.out.println("CANCEL!");
stmt.cancel();
} catch (Exception e) {
System.err.println("Statement.cancel() failed with: " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment