java - 如何使用 MySQL 连接器添加回调方法?
问题描述
我有一个存储库类,我在其中使用 MySQL Connector for Java 从我的数据库执行查询。
该方法在后台线程上运行,使用
new Thread(() -> {
...perform query
}).start();
public class CustomerRepository {
private ObservableList<Country> listCountries = FXCollections.observableArrayList();
public ObservableList<Country> getCountries() {
new Thread(() -> {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = ConnectionManager.getConnection().createStatement();
resultSet = statement.executeQuery(Constants.QUERY_GET_COUNTRIES);
while (resultSet.next()) {
int countryId = resultSet.getInt(Constants.TABLE_COUNTRIES_COL_COUNTRYID);
String country = resultSet.getString(Constants.TABLE_COUNTRIES_COL_COUNTRY);
String createDate = resultSet.getString(Constants.TABLE_COUNTRIES_COL_CREATEDATE);
String lastUpdate = resultSet.getString(Constants.TABLE_COUNTRIES_COL_LASTUPDATE);
Country countryObj = new Country(countryId, country, createDate, lastUpdate);
this.listCountries.add(countryObj);
}
} catch (SQLException e) {
System.out.println("Query Countries: " + e.getMessage());
} finally {
ConnectionManager.closeResultSetAndStatement(resultSet, statement);
}
}).start();
}
}
此代码引发Missing return statement
错误,因为我不知道如何返回实例变量listCountries
。
我将如何使用回调方法而不是new Thread(() -> {...
返回列表?原因是如果我不使用新线程,UI 将在执行查询时冻结。
解决方案
推荐阅读
- c++ - 获取文件扩展名原生方法
- wordpress - 论坛的最佳 Wordpress 主题?
- mongodb - ProductSchema 和 ReviewSchema 的 mongodb 模式设计
- mysql - 使用第一个查询的结果作为第二个查询的条件
- linux - 如何只允许特定用户将提交推送到主分支
- google-cloud-platform - 如何自动运行 Google Dataprep 作业?
- php - 为什么 DataTable 只加载 PHP/MySql 中 22 条记录中的 5 条?
- swift - 将此字符串转换为 PGN 表示法的快速方法是什么?
- javascript - Firefox 存储 API:基本数据保存不保存
- oracle - 将一个 DBCS 的数据访问到另一个 DBCS