java - 在第一次尝试中没有在preparedStatement 中更新ColumnNames
问题描述
public List<List<Object>> search( String table, String searchTerm) throws SQLException{
checkConnectionisValid();
checkTableNameAndColumnsAreValid(table);
List<List<Object>> list = new LinkedList<>();
try(PreparedStatement pstmt = connection.prepareStatement(buildSQLSearchQuery(table, true))) {
if (searchTerm!=null) {
searchTerm = String.format("%%%s%%", searchTerm);
for(int index=1;index<columnNames.size()+1;index++) {
pstmt.setObject(index, searchTerm);
}
extractRowsFromResultSet(pstmt, list);
System.out.println(pstmt);
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
//e.printStackTrace();
}
return list;
}
public List<String> getAndInitializeColumnNames(String table) throws SQLException{
checkConnectionisValid();
columnNames.clear();
DatabaseMetaData dbMeta = (DatabaseMetaData) connection.getMetaData();
ResultSet rs = dbMeta.getColumns(connection.getCatalog(), null, table, null);
while(rs.next()) {
columnNames.add(rs.getString("COLUMN_NAME"));
}
List<String> list = unmodifiableList(columnNames);
return list;
}
private void checkTableNameAndColumnsAreValid(String table) throws SQLException {
table = Objects.requireNonNull(table,"Table name cannot be null").trim();
if (tableNames.isEmpty()) {
getAndInitializeTableNames();
}
if (columnNames.isEmpty()) {
getAndInitializeColumnNames(table);
}
if (table.isEmpty() || !tableNames.contains(table)) {
throw new IllegalArgumentException("Table Name = \"" + table + "\"is not valid");
}
}
你好。我在我的数据库搜索应用程序中遇到了一个奇怪的错误。因此,当我第一次在任何表上搜索某些内容时,它工作得很好,但是当我更改表并第一次搜索时,它使用前一个表的列名而不是使用它的表并给出错误,但是当我再次单击搜索,列名得到更新,搜索通过。任何帮助将不胜感激 我在控制台中打印了 pstmt 并显示了输出
Button searchButton = createButton("Search",e-> {
try {
if (!controller.isConnected()) {
conectionStatus.setText("Must Connect First");
}
} catch (SQLException e1) {
e1.printStackTrace();
conectionStatus.setText("Failed" + e1.getMessage());
e1.printStackTrace();
}
conectionStatus.setText("Searching");
try {
List<List<Object>> list = controller.search(searchText.getText().trim());
if (list!=null) {
conectionStatus.setText("Populating Table");
populateTable(list);
conectionStatus.setText("Finished");
}
} catch (SQLException e1) {
e1.printStackTrace();
conectionStatus.setText("Failed" + e1.getMessage());
e1.printStackTrace();
}
});
解决方案
推荐阅读
- php - ErrorException:md5_file(/tmp/phptdn2a80.30601700 1609791282):无法打开流:没有这样的文件或目录
- python - 返回 True and None vs True and False 是 Pythonic 吗?
- python - Braintree Django 异常“只能将 str(不是“元组”)连接到 str”
- reactjs - React Hook clean/show Errors message while typing
- c# - 使用 SignalR 在 blazor 服务器中实现全局通知系统
- r - 从 acf 输出列表中提取特定元素
- python - Python中的@运算符是什么?
- javascript - 页面加载时如何触发javascript事件
- python - 程序如何以低电平输出声音?
- database - Terraform 布尔变量 true - 基于映射值