所以我是 JDBC - SQL Programming 的初学者。我需要一点建议,这很可能是关于 SYNTAX 的。
所以,问题 = 我正在尝试搜索记录中具有名称(函数参数中提供的字符串)的记录。以下是我的代码。现在,我以这样一种方式设计了这段代码,即可以有超过 1 条记录具有相同的名称,因此所有这些记录的数据都将被打印(通过 ShowData() 函数)。
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
原来如此。据我了解,RESULTSET rs 或我正在执行的 Query 存在一些问题. 请帮忙。 &如果您可以建议更好的搜索方法,请务必这样做。我将在同一模式上编写另外 4 个函数 SearchbyAge、SearchbyQualification、SearchbySpecialization。
最佳答案
这就够了
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
您不必使用 if
case 以这种方式检查结果集中的数据
if( !(rs.next()) )
这将移动到 resultset
中的下一条记录
关于java - JDBC 中的结果集搜索错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798178/