java - 从数据库循环加载数据

标签 java mysql swing for-loop

我想问:为什么当我加载我的程序时它没有出现?

我的程序是当我单击按钮时它将从我的数据库中的所有组件加载。我正在使用方法 getRow(); 中的循环。奇怪的是netbeans没有报错但是图片就是不想显示。我认为 SQL 没有错误。如何解决?

public void loaddata(){
try{
    ImageIcon img;
    koneksi_db();
    java.sql.Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery("Select * FROM component where UsernameID ='"+jLabel5.getText()+"' ");    // query for load as username login

    for (int i=1; i<rs.getRow(); i++){   // loading data using loop from get row
        rs.getRowId(i);
        JLabel draggy = new JLabel();
        String imagePath =  rs.getString("source");
        int x = rs.getInt("coordinatX");
        int y = rs.getInt("coordinatY");
        String nama = rs.getString("UniqueID");
        img = new ImageIcon(getClass().getResource(imagePath));
            draggy.setIcon(img);
            draggy.setText(nama);
            this.add(draggy);
            draggy.setBounds(x, y, 70, 70); //calling dragy (jlabel) in frame.
    }
    }catch(Exception e){

     JOptionPane.showMessageDialog(null,"error in sql");
    }
}

最佳答案

您的for循环未运行,因为 i<rs.getRow()总是false .

引用 ResultSet.getRow() 的javadoc :

Retrieves the current row number. The first row is number 1, the second number 2, and so on. [...] Returns the current row number; 0 if there is no current row

由于您从未检索过行,因此它返回 0 .

引用 ResultSet 的javadoc :

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

因此,您可以这样编写循环:

while (rs.next()) {
    // call rs.getXxx methods to retrieve column values
}

此外,不要通过使用字符串连接与用户输入的字符串来构建 SQL 语句。这将使您容易受到SQL Injection的影响。攻击,允许用户窃取或删除您的所有数据

相反,请使用 PreparedStatement :

String sql = "SELECT * FROM component WHERE UsernameID = ?";
try (PreparedStatement stmt = conn.prepareStatement()) {
    stmt.setString(1, jLabel5.getText());
    try (ResultSet rs = st.executeQuery()) {
        while (rs.next()) {
            // code here
        }
    }
}

关于java - 从数据库循环加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32625912/

相关文章:

java - Mockito findByIdOrNull 问题

php - 通过匹配日期查询获取详细信息

java - 有没有办法在 JLabel 中打印 AttributedString?

java - 我如何允许用户使用 Spring Security 覆盖?

java - Maven 编译器插件错误 : can't access enum (bad signature, bad class)

java - 如何在firestore中以时间戳的形式保存文本?

java - 如何为 JTable 复选框标题设置边框

mysql - SQL 查询返回按月分组的列总和,包括所有先前日期

php - MySQL 查询的 Union Join 问题

java - Java 中带有键绑定(bind)的 keyReleased() 方法?