JDBC 의 일반적인 첨삭 검사 작업(MySQL,반사)

43624 단어 DatabaseJavaDevelop
목차
  • JDBC 의 일반적인 첨삭 검사 조작(MySQL,반사)
  • 데이터베이스 연결 가 져 오기
  • 데이터베이스 업데이트:첨삭 수정
  • 데이터베이스 조회(반사)
  • 총화
  • 전체 코드
  • JDBCUtils
  • Update & Query
  • 잘못 되면 연락 주세요
  • JDBC 의 일반적인 첨삭 검사 작업(MySQL,반사)
    데이터베이스 연결 가 져 오기
  • jdbc 를 프로젝트 프로젝트 의 build path 에 먼저 추가 합 니 다
  • 프로필 작성,데이터 와 코드 분리.
  • url=jdbc:mysql://localhost:3306/database
    user=jdbctest
    password=jdbctest123
    className=com.mysql.cj.jdbc.Driver
    
  • 프로필 패키지 읽 기 연결 방법
  • 매번 데이터 베 이 스 를 연결 하 는 이 조작 을 사용 해 야 하기 때문에 우 리 는 이 를 하나의 클래스 에 밀봉 하여 정적 인 방법 으로 나타 납 니 다.
  • public static Connection getConnection(){
    	Connection conn = null;
    	try {
            // 1. Load properties file 
    		InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
    		Properties props = new Properties();
    		props.load(is);
            // 2. Get four elements
    		String url = props.getProperty("url");
    		String user = props.getProperty("user");
    		String password = props.getProperty("password");
    		String className = props.getProperty("className");
            // 3. Register Driver class
    		Class.forName(className);
            // 4. Get connector
    		conn = DriverManager.getConnection(url, user, password);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}		
    	return conn;
    }
    

    데이터베이스 업데이트:첨삭 수정
  • Prepared Statement 을 사용 하여 데이터 베 이 스 를 추가 삭제 하고 수정 합 니 다
  • Prepared Statement 을 사용 하여 SQL 문 구 를 미리 컴 파일 하여 Statement 의 SQL 주입 문 제 를 복원 합 니 다
  • 삭제 변경 에 있어 서 delete,insert,update 를 실행 한 후에 true/false 로 돌아 갈 수 있 습 니 다.그래서 우 리 는 이 세 가 지 를 같은 방법 에 쓸 수 있 습 니 다.반환 값 을 가 져 올 수도 있 고 반환 값 을 가 져 오지 않 을 수도 있 습 니 다.여기 서 우 리 는 반환 값 을 가 져 오지 않 습 니 다
  • /**
     * Update: update, insert, delete
     * 
     * @param sql your SQL statement
     * @param objs parameters in SQL replace placeholder
     */
    public void update(String sql, Object... objs) {
    	Connection conn = null;
    	PreparedStatement ps = null;
    	try {
           	// Get connector
    		conn = JDBCUtils.getConnection();
    		// PreparedStatement for precompiling sql statement
            ps = conn.prepareStatement(sql);
            // Replace the placeholders
    		for (int i = 0; i < objs.length; i++) {
    			ps.setObject(i + 1, objs[i]);
    		}
    		// Execute sql statement
    		ps.execute();
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
            // Close resources
    		JDBCUtils.closeResources(conn, ps);
    	}
    }
    

    데이터베이스 조회(반사)
  • 데이터 베 이 스 를 조회 하 는 작업 이 다 릅 니 다.첨삭 수정,조회 작업 은 결 과 를 되 돌려 주 는 작업 이 있 기 때문에 저 희 는 첨삭 수정 과 분리 하여 씁 니 다
  • .
  • 반환 결과 가 있 는 것 을 제외 하고 서로 다른 조회 에 대해 우리 가 돌아 온 결과 집의 유형 처리 방식 도 다르다
  • 우 리 는 반 사 를 사용 하여 우리 가 돌아 온 결과 집 을 동태 적 으로 처리 합 니 다.구체 적 인 조작 은 코드 를 참조 하 십시오.
  • /**
     * Using it for SQL query, and returns a list including objects
     * @param  Generics class
     * @param clazz pojo for your table
     * @param sql sql statement
     * @param objs parameter used by replacing placeholder
     * @return a list including all objects you get
     */
    public <T> List<T> query(Class<T> clazz, String sql, Object... objs) {
    	Connection conn = null;
    	PreparedStatement ps = null;
    	ResultSet rs = null;
    	List<T> list = null;
    	try {
            // 1. Get connector
    		conn = JDBCUtils.getConnection();
            // 2. PreparedStatement to precompile SQL statement
    		ps = conn.prepareStatement(sql);
            // 3. Repalce all placeholder
    		for (int i = 0; i < objs.length; i++) {
    			ps.setObject(i + 1, objs[i]);
    		}
            // 4. Excute SQL statement
    		rs = ps.executeQuery();
            // 5. Meta data is easier to process reslut set 
    		ResultSetMetaData rsmd = rs.getMetaData();
    		int ccount = rsmd.getColumnCount();
    		list = new ArrayList<T>();
    		while (rs.next()) {
    			T t = clazz.newInstance();
    			for (int i = 0; i < ccount; i++) {
    				Object columnValue = rs.getObject(i + 1);
    				String columnLabel = rsmd.getColumnLabel(i + 1);
    				// Using reflect to set the value for every column
    				Field field = clazz.getDeclaredField(columnLabel);
    				field.setAccessible(true);
    				field.set(t, columnValue);
    			}
    			list.add(t);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		JDBCUtils.closeResources(conn, ps, rs);
    	}
    	return list;
    }
    
  • 상기 방법 에 대한 설명
  • 상기 방법 에서 우 리 는 일반적인 방법 을 사 용 했 습 니 다.주로 서로 다른 데이터 시트 의 자바 빈 에 대해 서로 다른 결과 집합 이 발생 하 는 상황 을 처리 하기 위해 서 입 니 다.주의:반환 값 의 어댑터 를 잊 지 마 세 요
  • 결과 집합 을 처리 할 때 우 리 는 결과 집합 의 메타 데 이 터 를 사용 하여 데 이 터 를 더욱 편리 하 게 처리 하고 아래 의 반사 동적 설정 값
  • 도 편리 하 다.
  • 결과 가 집 중 된 데 이 터 를 처리 할 때 우 리 는 반사 동적 으로 새로운 대상 의 각 값 을 설정 했다.주의해 야 할 것 은 우리 의 SQL 문장의 자리 표시 자 와 결과 가 집 중 된 각 데이터 의 첫 번 째 데 이 터 는 모두 1 이 므 로 우리 가 순환 할 때 사용 하 는 index 는 i+1
  • 이다.

    총결산
  • 데이터 뱅 크 의 삭제 와 검 사 는 두 가지 로 나 뉘 는데 하 나 는 결과 집합 이 발생 하지 않 은 삭제 와 수정 이 고 다른 하 나 는 결과 집합 이 있 는 조회 작업
  • 이다.
  • 자리 차지 문자 와 조회 결과 집합 을 교체 할 때 아래 는 1 부터 기 존의 0 부터(같은 외국인,다른 아래 표)
  • 와 다르다.
  • 우리 jdk 1.8 의 새로운 특성 에 trywith_resources 의 방법 으로 원래 의 try 를 교체 하 였 습 니 다.catch_finally 는 자동 으로 스 트림 을 닫 는 작업 을 수행 합 니 다.사용 하기에 매우 편리 합 니 다.그러나 이 Connection 과 Prepared Statement,ResultSet 은 더 이상 할당/지정 되 지 않 기 때문에 닫 을 때 전통 적 인 스 트림 을 닫 는 방법 입 니 다.
  • 그리고 try 사용with_resources 자동 으로 스 트림 을 닫 는 작업 은 자바.lang.AutoCloseable 인터페이스
  • 를 실현 해 야 합 니 다.
    전체 코드
    JDBCUtils
  • JDBC 도구 류,연결 가 져 오기 및 스 트림 닫 기 동작
  • 
    /**
     * 
     * @author Master_Joe
     *
     */
    public class JDBCUtils {
    	/**
    	 * @return SQL Connectors
    	 */
    	public static Connection getConnection(){
    		Connection conn = null;
    		try {
    			InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
    			Properties props = new Properties();
    			props.load(is);
    			
    			String url = props.getProperty("url");
    			String user = props.getProperty("user");
    			String password = props.getProperty("password");
    			String className = props.getProperty("className");
    			
    			Class.forName(className);
    			
    			conn = DriverManager.getConnection(url, user, password);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}		
    		return conn;
    	}
    	
    	/**
    	 * Close resources connector and statement
    	 * @param conn SQL connector
    	 * @param statement
    	 */
    	public static void closeResources(Connection conn, Statement statement) {
    		try {
    			if (conn != null) {
    				conn.close();
    			}
    			if (statement != null) {
    				statement.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	/**
    	 * Close resources including Connectors, Statement and ResultSet
    	 * @param conn SQL connector 
    	 * @param statement
    	 * @param rs ResultSet 
    	 */
    	public static void closeResources(Connection conn, Statement statement, ResultSet rs)  {
    		if (conn != null) {
    			try {
    				conn.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		if (statement!=null) {
    			try {
    				statement.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		if(rs != null) {
    			try {
    				rs.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		
    	}
    }
    
    

    Update & Query
    업데이트 및 조회 작업 을 실현 하 였 습 니 다.
    /**
     * Update & Query for SQL
     * 
     * @author Master_Joe
     *
     */
    public class Operating {
    
    	@Test
    	public void testOperating() {
    		String sql = null;
    		Object[] objs = new Object[] {};
    
    		update(sql, objs);
    		List<Operating> list = query(Operating.class, sql, objs);
    
    		list.forEach(System.out::println);
    	}
    
    	/**
    	 * Update: update, insert, delete
    	 * 
    	 * @param sql
    	 * @param objs
    	 */
    	public void update(String sql, Object... objs) {
    		Connection conn = null;
    		PreparedStatement ps = null;
    		try {
    			conn = JDBCUtils.getConnection();
    			ps = conn.prepareStatement(sql);
    			for (int i = 0; i < objs.length; i++) {
    				ps.setObject(i + 1, objs[i]);
    			}
    
    			ps.execute();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			JDBCUtils.closeResources(conn, ps);
    		}
    	}
    
    	/**
    	 * Using it for SQL query, and returns a list including objects
    	 * 
    	 * @param    Generics class
    	 * @param clazz pojo for your table
    	 * @param sql   sql statement
    	 * @param objs  parameter used by replacing placeholder
    	 * @return a list including all objects you get
    	 */
    	public <T> List<T> query(Class<T> clazz, String sql, Object... objs) {
    		Connection conn = null;
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		List<T> list = null;
    
    		try {
    			conn = JDBCUtils.getConnection();
    			ps = conn.prepareStatement(sql);
    			for (int i = 0; i < objs.length; i++) {
    				ps.setObject(i + 1, objs[i]);
    			}
    
    			rs = ps.executeQuery();
    			ResultSetMetaData rsmd = rs.getMetaData();
    			int ccount = rsmd.getColumnCount();
    			list = new ArrayList<T>();
    			while (rs.next()) {
    				T t = clazz.newInstance();
    				for (int i = 0; i < ccount; i++) {
    					Object columnValue = rs.getObject(i + 1);
    					String columnLabel = rsmd.getColumnLabel(i + 1);
    					// reflect to set the value for every column
    					Field field = clazz.getDeclaredField(columnLabel);
    					field.setAccessible(true);
    					field.set(t, columnValue);
    				}
    				list.add(t);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return list;
    	}
    }
    
  • 설명:
  • 이상 의 테스트 방법 중 sql 및 자리 차지 문자 의 교체
  • 를 사용자 정의 하 십시오.

    잘못 이 있 으 면 연락 주세요.
    작성 자 메 일:[email protected]

    좋은 웹페이지 즐겨찾기