2016-12-24 72 views
2

我是新来的Java和挣扎了一下。为什么此过程在MYSQL中运行,而不是在Java中运行?

我已经成立了一个程序在mysql中返回员工详细信息输入姓氏时:

CREATE PROCEDURE getEmployeeByLastName(IN in_last_name VARCHAR(16)) 
SELECT emp_no, first_name, last_name, gender, hire_date FROM oop_employees 
WHERE last_name = in_last_name; 

当我执行它这个工程在phpMyAdmin。

在我的Java的主要方法我要求用户输入姓氏......

System.out.println("Please enter the last name of the employee."); 
String last_name = keyboard.next(); 
Employee emp = getEmployeeByLastName(dbc.getConnection(), last_name);   
System.out.println(emp); 

getEmployeeByLastName是:

public static Employee getEmployeeByLastName(Connection conn, String lname) { 
    Employee emp = null; 
    try { 
     String sql = "CALL getEmployeeByLastName(\""+ lname +"\")"; 
     Statement st = conn.createStatement(); 
     ResultSet rs = st.executeQuery(sql);  
     while (rs.next())  
      emp = new Employee(rs.getInt("emp_no"), rs.getDate("birth_date"),rs.getString("first_name"),rs.getString("last_name"), rs.getString("gender"),rs.getDate("hire_date")); 
      rs.close(); 
      st.close(); 
    } 
    catch (SQLException e) { 
     e.printStackTrace(); 
    } 
    return emp; 
} 

当我搜索一个姓,我得到几个SQL异常错误,以及两个错误在上面的代码:

emp = new Employee(rs.getInt("emp_no"), rs.getDate("birth_date"),rs.getString("first_name"),rs.getString("last_name"), rs.getString("gender"),rs.getDate("hire_date")); 

和..

Employee emp = getEmployeeByLastName(dbc.getConnection(), last_name); 

我能够创建其他程序,使用雇员类来显示数据库中的数据,这是我第一个需要用户输入的过程。

是否有一个明显的原因,为什么这是在mysql中工作,但不是在eclipse中?所有帮助非常感谢,我发现这很难调试。请让我知道是否需要更多信息。

编辑:

例外

at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862) 
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1076) 
at com.mysql.jdbc.ResultSetImpl.getDate(ResultSetImpl.java:2034) 
+1

什么是例外?发布最小堆栈跟踪 – developer

+1

在您的问题中包含例外 – Yousaf

+2

'rs。getDate(“birth_date”)' - 我不知道这是否是唯一的错误,但是您的过程不会获取该列。 – Eran

回答

2

您查询您oop_employees表中选择5列:

SELECT emp_no, first_name, last_name, gender, hire_date FROM oop_employees 

但你的Java代码试图从ResultSet读6列:

emp = new Employee(rs.getInt("emp_no"), rs.getDate("birth_date"),rs.getString("first_name"),rs.getString("last_name"), rs.getString("gender"),rs.getDate("hire_date")); 

你忘了,包括在birth_date列的SQL语句。

1

此问题,因为JDBC代码无法解析的结果集。该过程很好,但Java代码需要修复。 SQL和结果集有所不同。正如其他评论员(@Eran)指出的那样,您只需在SQL中选择5列。

SELECT emp_no, first_name, last_name, gender, hire_date FROM oop_employees WHERE last_name = in_last_name; 

但您期待结果集查找6列。

emp = new Employee(rs.getInt("emp_no"), rs.getDate("birth_date"),rs.getString("first_name"),rs.getString("last_name"), rs.getString("gender"),rs.getDate("hire_date")); 

在SQL中添加“birth_date”列,然后重试。

另外,请在发布问题时粘贴完整的堆栈跟踪。您提供的堆栈跟踪不完整。

相关问题