我想问:为什么当我加载我的程序时它没有出现?
我的程序是当我单击按钮时它将从我的数据库中的所有组件加载。我正在使用方法 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. Thenext
method moves the cursor to the next row, and because it returnsfalse
when there are no more rows in theResultSet
object, it can be used in awhile
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/