我编写此代码是为了显示拥有最高薪水的员工的姓名 但当输出不正确时,它显示为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.
答案 0 :(得分:5)
试试这个SQL语句:
select fName, max(salary) from task4table
您的代码存在问题:
在此循环中,您将迭代到结果集的末尾:
while (r1.next()) {
size++;
}
然后,当你想再次迭代时
while (r1.next()) {
salaries[count]= r1.getInt("salary");
Names[count]= r1.getString("fName")+""+r1.getString("lName");
count++;
}
r1.next()
返回false
,因此不会发生此迭代。您可以在一个循环中执行此操作,也可以再次执行查询。但是,正如我所说的那样,使用max
使用正确的sql语句。
答案 1 :(得分:3)
您更改查询以获取单个查询中的所有最高工资人员
PreparedStatement st = con.prepareStatement("
select fName, lName, salary from task4Table where salary =
(select max(salary) from task4Table)");
ResultSet r1 = st.executeQuery();
迭代此结果集。
答案 2 :(得分:2)
您的代码存在 lot 错误,但这是您的直接问题:您没有正确找到最大值。
正确的方法是使用SQL,正如我上面的答案所示。如果你坚持走自己的路,试试这个:
int maxSalary = Integer.MIN_VALUE;
for (int i = 0; i < salaries.length; i++) {
if (salaries[i] > maxSalary) {
maxSalary = salaries[i];
}
}
你的编码风格不好。您需要对括号放置,空格,空行等保持一致。您还应该记住并遵循Sun Java编码约定。
答案 3 :(得分:2)
请尝试以下代码:
public static void displayMaxSalary() throws ClassNotFoundException, SQLException
{
String maxSalary;
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 order by salary desc limit 1");
ResultSet r1=st.executeQuery();
if(r1.next()) {
maxSalary = r1.getString("fName")+""+r1.getString("lName");
}
System.out.println("The name of employee who has the higher salary is :");
System.out.println( maxSalary);
} //end-displayMaxSalary.