public class DAO {
public void update(String sql, Object... args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCTools.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.close(null, ps, conn);
}
}
public T get(Class clazz, String sql, Object... args) {
T entity = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCTools.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
Map<String, Object> values = new HashMap<String, Object>();
ResultSetMetaData rmsd = rs.getMetaData();
if (rs.next()) {
for (int i = 0; i < rmsd.getColumnCount(); i++) {
String columnLabel = rmsd.getColumnLabel(i + 1);
Object columnValue = rs.getObject(i + 1);
values.put(columnLabel, columnValue);
}
}
if (values.size() > 0) {
entity = clazz.newInstance();
for (Map.Entry<String, Object> map : values.entrySet()) {
String fieldName = map.getKey();
Object fieldValue = map.getValue();
BeanUtils.setProperty(entity, fieldName, fieldValue);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.close(rs, ps, conn);
}
return entity;
}
}
public class DAOTest {
DAO dao = new DAO();
@Test
public void testUpdate() {
String sql = "INSERT INTO customers(name,email,birth)VALUES(?,?,?)";
dao.update(sql, "XiaoWang", "[email protected]", new Date(
new java.util.Date().getTime()));
}
@Test
public void testGet() {
String sql="SELECT flow_id flowId, type, id_card iDCard, "
+ "exam_card examCard, student_name studentName, "
+ "location, grade " + "FROM examstudent WHERE flow_id = ?";
Student stu=dao.get(Student.class, sql, 9);
System.out.println(stu);
}
}