当前位置 : 主页 > 编程语言 > 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 getNoneInsertSql(Class
  
    c,List
   
     list){ StringBuffer sb=new StringBuffer(); sb.append("insert into "); sb.append(c.getSimpleName()); sb.append(" values("); for(String s: list){ sb.append("?"); sb.append(","); } sb.delete(sb.length()-1, sb.length()); sb.append(")"); return sb.toString(); }
   
  
 
实现增加和测试
public static 
 
   int insertAllFactory(T t){
		int i=1;
		Class c=t.getClass();
		List
  
    list=new ArrayList
   
    (); for(Field f : c.getDeclaredFields()){ list.add(f.getName()); } String sql=getNoneInsertSql(c,list); try { PreparedStatement pstt=getConnection().prepareStatement(sql); for(String s : list){ for(Method me : c.getDeclaredMethods()){ if(me.getName().equalsIgnoreCase("get"+s)){ try { pstt.setObject(i, me.invoke(t, null)); i++; } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } return pstt.executeUpdate(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ close(); } return 0; } public static void test(Users users){ if( insertAllFactory(users)>0){ System.out.println("成功"); }else{ System.out.println("失败"); } }
   
  
 
网友评论