gpt4 book ai didi

JDBC 的 Java 线程

转载 作者:行者123 更新时间:2023-11-30 09:04:16 25 4
gpt4 key购买 nike

我有带有 JDBC 的 GUI 应用程序。一个线程用于 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 中显示数据库中的数据。

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;

}

我想知道如何添加一个新线程,以便所有数据库操作都在一个单独的线程中运行,而不是这个线程 Swing 。

最佳答案

ExecutorService 类为例。

ExecutorService exec = Executors.newFixedThreadPool(2);
exec.execute(new Runnable() {
// Run your database thread

});
exec.shutdown();

关于JDBC 的 Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com