gpt4 book ai didi

java - 组合框 : java. sql.SQLException 中的错误:游标状态无效 - 没有当前行

转载 作者:行者123 更新时间:2023-11-29 08:36:16 24 4
gpt4 key购买 nike

我一直收到这个错误。

我有一个组合框,里面装满了数据库的元素,我希望它能使选定的选项出现在文本框中,但出现此错误。它只适用于第一个结果: enter image description here

代码如下:

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);
}
}

最佳答案

检查 ResultSet#next() 以查看是否确实有一行可用。

此外,始终使用 PreparedStatement。它们有助于降低 SQL 注入(inject)攻击的风险。

通常的成语是:

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
}

关于java - 组合框 : java. sql.SQLException 中的错误:游标状态无效 - 没有当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43943804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com