import java.sql.*;
public class Db {
private static Connection conn = null;
public static Connection getCon(){
try{
Class.forName("com.mysql.jdbc.Driver");//加载数据库连接驱动
String user="root";//用户名
String pwd="root";//密码
String url="jdbc:mysql://localhost:3306/test";//连接URL
conn=DriverManager.getConnection(url, user, pwd);//获取连接
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}
/**
* 查询员工信息
* @return 员工信息的List<Employee>集合
*/
public List<Employee> selectEmployee(){
List<Employee> list = new ArrayList<Employee>();
Connection con = null;
try{
con = Db.getCon();
Statement stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery("select * from tb_employee");
while(rs.next()){
Employee emp = new Employee();
emp.setEmpAge(rs.getInt("empAge"));
emp.setEmpDuty(rs.getString("empDuty"));
emp.setEmpName(rs.getString("empName"));
emp.setEmpSex(rs.getString("empSex"));
list.add(emp);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
return list;
}
/**
* 保存员工信息
* @param args
*/
public boolean saveEmployee(Employee emp){
boolean result = false;
Connection con = null;
try{
con = Db.getCon();
String sql = "insert into tb_employee(empName,empAge,empSex,empDuty)values(?,?,?,?)";
PreparedStatement stmt = (PreparedStatement) con.prepareStatement(sql);
stmt.setString(1, emp.getEmpName());
stmt.setInt(2, emp.getEmpAge());
stmt.setString(3, emp.getEmpSex());
stmt.setString(4, emp.getEmpDuty());
int i = stmt.executeUpdate();
if(i == 1) result = true;
}catch(Exception e){
e.printStackTrace();
}finally{
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
return result;
}