首页 > 解决方案 > 在第一次尝试中没有在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();
    }
     });

标签: javasqljdbc

解决方案


推荐阅读