我想检查新输入的数据是否已经在表格中
码
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
错误:
Exception:java.sql.SQLException: Illegal operation on empty result set.
答案 0 :(得分:0)
您需要首先检查ResultSet
以检查它是否包含行:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
答案 1 :(得分:0)
当select语句返回空集时,会出现此异常。添加一个try / catch块,它根据知道数据不在catch块的表中。
答案 2 :(得分:0)
您需要检查结果集是否包含元素:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
答案 3 :(得分:0)
检查数据库中是否存在特定记录的最简单方法可能如下:
Select 1 from bank where No = [your_supplied_value]
如果在数据库中使用提供的数据找到一行或返回空结果集,则此查询将返回1。因此,您需要检查的是结果集中是否返回任何值或者是否为emtpy。
以下是一个示例代码,可帮助您入门:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
我希望这不是你的最终代码,因为它有几个问题:
您无法正确管理资源。完成查询数据库后,应考虑关闭结果集,语句和连接对象。
请注意,我检查了JTextField中的文本是否为空。当您知道文本字段中没有值时,这是阻止调用数据库的好方法。
我建议使用PreparedStatement而不是Statement来查询数据库。
答案 4 :(得分:0)
ResultSet
最初位于之前第一行。因此,在调用其中一个next()
方法之前,您需要调用true
将其移至下一行(并检查它是否返回getXXX()
)。
答案 5 :(得分:0)
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}