我写了这段代码是为了显示拥有最高工资的员工的名字,但是当输出不正确时,它显示为null而不是"mmm kkk"!! 虽然我填写了表格,但这是内容:
这是我的代码,任何人都可以帮助我?:(
public static void displayMaxSalary() throws ClassNotFoundException, SQLException
{
int size=0;
int count=0;
String maxSalary=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/task4DB?"
+ "user=root&password=123");
PreparedStatement st = con.prepareStatement("select * from task4Table ");
ResultSet r1=st.executeQuery();
while (r1.next()) {
size++;
}
int salaries[]=new int[size];
String Names[]=new String[size];
while (r1.next()) {
salaries[count]= r1.getInt("salary");
Names[count]= r1.getString("fName")+""+r1.getString("lName");
count++;
}
for(int i=1;i< salaries.length;i++)
{
if(salaries[i]>salaries[i-1])
{
maxSalary= Names[i];
}
}
System.out.println("The name of employee who has the higher salary is :");
System.out.println( maxSalary);
} //end-displayMaxSalary.
Run Code Online (Sandbox Code Playgroud)
试试这个SQL语句:
select fName, max(salary) from task4table
Run Code Online (Sandbox Code Playgroud)
你的代码有问题:
在此循环中,您将迭代到结果集的末尾:
while (r1.next()) {
size++;
}
Run Code Online (Sandbox Code Playgroud)
然后,当你想再次迭代时
while (r1.next()) {
salaries[count]= r1.getInt("salary");
Names[count]= r1.getString("fName")+""+r1.getString("lName");
count++;
}
Run Code Online (Sandbox Code Playgroud)
r1.next()返回false所以这个迭代不会发生.您可以在一个循环中执行此操作,也可以再次执行查询.但是,正如我所说,用适当的sql语句使用它max.