我一直收到这个错误。
我有一个填充了数据库元素的组合框,我希望它能使所选选项出现在文本框中,但是我收到了这个错误。它仅适用于第一个结果:
这是代码:
private void cmbx_vendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String url = "jdbc:informix-sqli://192.168.2.3:1525/cubo:INFORMIXSERVER=myserver;user=infx;password=infx";
Connection con1 = DriverManager.getConnection(url);
System.out.println("Cubo conectada combobox");
Statement st1= con1.createStatement();
ResultSet rs1=st1.executeQuery("SELECT * FROM cartsusc WHERE vendedor = '"+this.cmbx_vend.getSelectedItem()+"'");
rs1.next();
this.txt_dato.setText(rs1.getString("vendedor"));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
答案 0 :(得分:2)
你必须使用:
if(rs1.next()){
this.txt_dato.setText(rs1.getString("vendedor"));
}
不要像这样设置参数,这可能会导致语法错误或SQL注入,相反,您必须使用PreparedStatement作为示例:
String query = "SELECT * FROM cartsusc WHERE vendedor = ?";
try (PreparedStatement pstm = connection.prepareStatement(query)) {
pstm.setString(1, this.cmbx_vend.getSelectedItem());
ResultSet rs1 = pstm.executeQuery();
if(rs1.next()){
this.txt_dato.setText(rs1.getString("vendedor"));
//this.txt_dato.setText(rs1.getString(1));//or you can get your result like this
}
}
完成后别忘了关闭你的陈述和联系。
答案 1 :(得分:2)
检查ResultSet#next()
以查看是否确实有一行可用。
另外,请始终使用PreparedStatement。它们有助于降低SQL注入攻击的风险。
通常的习语是:
try {
Connection conn = getConnection();
try {
String sql = "SELECT * FROM cartsusc WHERE vendedor = ?";
PreparedStatement ps = conn.prepareStatement(sql);
try {
ps.setString(1, this.cmbx_vend.getSelectedItem());
ResultSet rs = ps.executeQuery();
try {
if (rs.next()) {
this.txt_dato.setText(rs1.getString("vendedor"));
}
} finally {
rs.close();
}
} finally {
ps.close();
}
} finally {
conn.close();
}
} catch (SQLException e) {
//handle
}
从Java 7开始,您可以使用try-with-resources自动关闭资源:
String sql = "SELECT * FROM cartsusc WHERE vendedor = ?";
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
) {
ps.setString(1, this.cmbx_vend.getSelectedItem());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
this.txt_dato.setText(rs1.getString("vendedor"));
}
}
} catch (SQLException e) {
//handle
}