JDBC的Java线程 [英] Java thread for JDBC
本文介绍了JDBC的Java线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带JDBC的GUI应用程序.一个线程用于摆动gui.
I have GUI application with JDBC. One thread is for swing gui.
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
try {
runApp();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
程序启动后,在JTable中显示数据库中的数据.
After starting the program displays my data from the database in a JTable.
public List<Category> getCategory() throws SQLException
{
List<Category> cat = new ArrayList<Category>();
Connection conn = Database.getInstance().getConnection();
System.out.println(conn);
String sql = "select id, name from kategorie";
Statement selectStatement = conn.createStatement();
ResultSet results = selectStatement.executeQuery(sql);
while(results.next())
{
int id = results.getInt("id");
String name = results.getString("name");
Category category = new Category(id, name);
cat.add(category);
}
results.close();
selectStatement.close();
return cat;
}
我想知道如何添加一个新线程,以便所有数据库操作都在单独的线程中运行,而不是在该线程摆动中运行.
I wonder how can I add a new thread so that all database operations run in a separate thread, not this thread swing.
推荐答案
以ExecutorService
类为例.
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.execute(new Runnable() {
// Run your database thread
});
exec.shutdown();
这篇关于JDBC的Java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文