【发布时间】:2014-01-14 21:31:56
【问题描述】:
所以我是JDBC - SQL 编程 的初学者。我需要一点建议,很可能是关于 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。
【问题讨论】:
-
但是你忘了说错误是什么:)
-
您的显示数据功能也可能有错误。我会将查询打印到标准输出。然后,您可以在数据库窗口中复制并粘贴它,看看它是否有效。
-
@PeteBelford:先生,这种方法没用。我已经测试了我的 ShowData() 函数,它可以 100% 工作。
标签: java mysql sql jdbc resultset