这里我运用的是jdbc连接数据库,运用三层架构的思想
首先我写了两个工具类 JDBCUtils和JDBCTemplate,用来连接数据库和动态获取sql语句和获取实体类的方法
JDBCTemplate
public class jdbcTemplate {
public final static String TABLE_PREFIX="";
private static String tableName="";
private static Field[] fields;
public static List getFields(Object obj){
Class c=obj.getClass();
String className=obj.getClass().getSimpleName();
// TABLE_PREFIX+
tableName=className.toLowerCase();
fields=c.getDeclaredFields();
Method[]method=c.getMethods();
List list=new ArrayList();
for (int i=0;i<fields.length;i++){
String m="get"+fields[i].getName().toUpperCase().charAt(0)+fields[i].getName().substring(1);
for (int j=0;j<method.length;j++){
if (method[j].getName().endsWith(m)){
try {
list.add(method[j].invoke(obj,null));
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
}return list;
}
public static String getUpdateSQL(Object obj){
List list=getFields(obj);
StringBuffer sql=new StringBuffer();
sql.append("UPDATE");
sql.append("`"+tableName+"`");
sql.append("SET");
for (int i=1;i<fields.length;i++){
if (!list.get(i).equals("")){
sql.append("`"+fields[i].getName()+"`");
sql.append("=?");
if (!list.get(i+1).equals("")){
sql.append(",");
}
}
}
sql.append("WHERE");
sql.append(" ");
sql.append(fields[0].getName());
sql.append("=?");
System.out.println(sql.toString());
return sql.toString();
}
}
运用反射动态的获取实体类里面的get方法,运用stringbuffer凭借反射获取实体类属性名并且拼接成SQL语句
JDBCUtils
public class JDBCUtils { /** * * @Description 获取数据库的连接 * @author shkstart * @date 上午9:11:23 * @return * @throws Exception */ public static Connection getConnection() throws Exception { // 1.读取配置文件中的4个基本信息 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 2.加载驱动 Class.forName(driverClass); // 3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); return conn; } /** * * @Description 关闭连接和Statement的操作 * @author shkstart * @date 上午9:12:40 * @param conn * @param ps */ public static void closeResource(Connection conn,Statement ps){ try { if(ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * * @Description 关闭资源操作 * @author shkstart * @date 上午10:21:15 * @param conn * @param ps * @param rs */ public static void closeResource(Connection conn,Statement ps,ResultSet rs){ try { if(ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
下面是Dao层代码
StudentDao接口
public interface StudentDao {
Student findOneById(int id) throws Exception;
Student login(String name,String password) throws Exception;
void addOne(Student student) throws Exception;
int update(Object obj) throws Exception;
void delete(int id) throws Exception;
}
StudentDaoimpl
@Override
public int update(Object obj) throws Exception {
Connection conn = JDBCUtils.getConnection();
List list= com.util.jdbcTemplate.getFields(obj);
String sql=jdbcTemplate.getUpdateSQL(obj);
PreparedStatement ps=conn.prepareStatement(sql);
int count=1;
for (int i=1;i<list.size();i++){
if (!list.get(i).equals("")) {
System.out.println(list.get(i));
ps.setObject(count++, list.get(i));
}
}
ps.setInt(count,(Integer) list.get(0));
int result=ps.executeUpdate();
JDBCUtils.closeResource(conn,ps);
return result;
}
这里运用反射获取实体类里面属性,判断是否为空为空不执行prepareStatement的传参
Service层
StduentService接口
public interface StudentService {
boolean lginStu(String name,String password)throws Exception;
void register(Student student)throws Exception;
String update()throws Exception;
}
StudentServiceimpl
public String update()throws Exception {
Scanner sc=new Scanner(System.in);
boolean flag=false;
Student student=new Student();
Class c=student.getClass();
Field[] fields=c.getDeclaredFields();
Method[]method=c.getMethods();
for (int i=0;i<fields.length;i++) {
String m = "set" + fields[i].getName().toUpperCase().charAt(0) + fields[i].getName().substring(1);
for (int j = 0; j < method.length; j++) {
// System.out.println(method[j].getName());
if (method[j].getName().endsWith(m)){
System.out.println(method[j].getName());
if (method[j].getName().equals("setId")){
System.out.println("请输入id");
String id=sc.nextLine();
int id1=Integer.parseInt(id);
method[j].invoke(student,id1);
}else {
String s = sc.nextLine();
method[j].invoke(student, s);
}
}
}
}
int result=studentDao.update(student);
if (result!=0){
return "修改成功";
}else {
return "修改失败";
}
// studentDao.update();
}
这里运用反射获取set方法对用户输入的数据进行传入对象
View层
public void update() throws Exception {
System.out.println( studentService.update());
}
到此无论使用哪个实体类都可以动态修改数据库数据