当前位置 : 主页 > 编程语言 > c++ >

通过反射实现一张表的删除

来源:互联网 收集:自由互联 发布时间:2021-07-03
数据库的连接 {try {Class.forName("oracle.jdbc.driver.OracleDriver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static Connection getConnection(){try {Connection conn=DriverManag
数据库的连接
{
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static Connection getConnection(){
		try {
			Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","C##admin","123456");
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	private static void close(){
		if(getConnection()!=null){
			try {
				getConnection().close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
自动生成sql语句
public static 
 
   String getNoneDeleteSql(Class
  
    c){ StringBuffer sb=new StringBuffer(); sb.append("delete from "); sb.append(c.getSimpleName()); sb.append(" where id=?"); return sb.toString(); }
  
 
实现删除和测试
public static 
 
   int deleteAllFactory(T t){
		Class c=t.getClass();
		String sql=getNoneDeleteSql(c);
		try {
			PreparedStatement pstt=getConnection().prepareStatement(sql);
			for(Method me : c.getDeclaredMethods()){
				if(me.getName().equalsIgnoreCase("getid")){
					pstt.setObject(1, me.invoke(t, null));
					return pstt.executeUpdate();
				}
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}


    public static void test(Users users){
    if( deleteAllFactory(users)>0){
        System.out.println("成功");
    }else{
        System.out.println("失败");
    }
}
 
网友评论