//引包如下
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
规范写法:
public static void main(String[] args) {
// 查询XX部门员工的全部信息。
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysqldb";
String username = "root";
String password = "root";
con =DriverManager.getConnection(url,username,password);
Scanner sc =new Scanner(System.in);
System.out.println("请输入部门编号");
String newdeptno = sc.nextLine();
String sql ="select * from emp where deptno = ?";
ps = con.prepareStatement(sql);
ps.setString(1,newdeptno);
rs = ps.executeQuery();
List<Emp> elist = new ArrayList<Emp>();
while(rs.next()) {
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
Date hiredate = rs.getDate("hiredate");
double sal = rs.getDouble("sal");
double comm = rs.getDouble("comm");
int deptno = rs.getInt("deptno");
System.out.println(deptno);
Emp e = new Emp();
e.setEmpno(empno);
e.setEname(ename);
e.setJob(job);
e.setMgr(mgr);
e.setHiredate(hiredate);
e.setSal(sal);
e.setComm(comm);
e.setDeptno(deptno);
elist.add(e);
for(Emp t:elist) {
System.out.println(t.toString());
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}finally {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}finally {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}
}
}
}
}