数据在** Result.next()**循环中被覆盖

时间:2013-12-13 02:37:32

标签: java swing jdbc jtable resultset

我有一个搜索按钮进入我的数据库并搜索一个名称,但是当有两个相同名称的条目时,它只会让我回来一个,我无法弄清楚原因。以下是我现在使用的代码。

 public boolean search(String str1, String username){//search function for the access history search with two parameters
    boolean condition = true;
    String dataSourceName = "securitySystem";//setting string datasource to the securitySystem datasource
    String dbUrl = "jdbc:odbc:" + dataSourceName;//creating the database path for the connection
    try{
        //Type of connection driver used    
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        //Connection variable or object param: dbPath, userName, password
        Connection con = DriverManager.getConnection(dbUrl, "", "");

        Statement statement = con.createStatement();//creating the statement which is equal to the connection statement

        if (!(username.equals(""))){
            PreparedStatement ps = con.prepareStatement("select * from securitysystem.accessHistory where name = ?");//query to be executed
            ps.setString(1, username);//insert the strings into the statement
            ResultSet rs=ps.executeQuery();//execute the query
            if(rs.next()){//while the rs (ResultSet) has returned data to cycle through
                JTable table = new JTable(buildTableModel(rs));//build a JTable which is reflective of the ResultSet (rs)
            JOptionPane.showMessageDialog(null, new JScrollPane(table));//put scrollpane on the table
        }
        else{
                JOptionPane.showMessageDialog(null,"There has been no system logins at this time");// else- show a dialog box with a message for the user
            }
}
statement.close();//close the connection
    } catch (Exception e) {//catch error
        System.out.println(e);
    }
    return condition;   
}

2 个答案:

答案 0 :(得分:2)

以下是如何使用TableModel向表格添加数据的示例。

假设您有这些初始模型条件

String[] columnNames = {"Column1", "Column2", "Column3"};
DefaultTableModel model = new DefaultTablModel(columnNames, 0);
JTable table = new JTable(model);

...

你应该像这样做某事

while (rs.next()){
    String s1 = rs.getString(1);
    String s2 = rs.getString(2);
    String s3 = rs.getString(3);

    Object[] row = {s1, s2, s3};

    model.addRow(row);
}

编辑:要直接从数据库获取列名,您需要使用ResultSetMetaData

尝试使用此方法。

public DefaultTableModel buildTableModel(ResultSet rs){

    ResultSetMetaData rsMeta = rs.getMetaData();
    int cloumns = rsMeta.getColumnCount();

    String columnNames = new String[columns];
    for (int i = 1; i <= columns; i++){
        columnNames[i - 1] = rsMeta.getColumnName(i);
    }

    DefaultTableModel model = new DefaultTableModel(columnNames, 0);

    while (rs.next()){
        // Just an example retrieving data. Fill in what you need
        String s1 = rs.getString(1);
        String s2 = rs.getString(2);
        String s3 = rs.getString(3);

        Object[] row = {s1, s2, s3};

        model.addRow(row);
        // End example
    }

    return model;
}

然后,

if (rs != null){
    JTable table = new JTable(buildTableModel(rs));
}

答案 1 :(得分:2)

您的代码多次调用rs.next()。您在上面的搜索方法中调用buildTableModel(...)方法之前调用它,实质上是浪费了一行您从未使用过的数据。

相反,只需将ResultSet传递给方法而不在其上调用next,然后使用buildTableModel(...) 中的while循环来填充数据向量。如果向量为空,则抛出异常,或返回0行的TableModel。