• JDBC实现用于操作数据库Mysql的工具类JDBCTools


      下面用一个统一的工具类封装一套用于数据库的JDBC操作:包括 1)获取数据库链接资源  2)释放数据库链接资源,包括Connection,Statement,PreparedStatement,ResultSet等 3)数据库的更新操作,包括插入,删除,修改  4)数据库的查询操作

      首先是1)获取数据库链接资源

         /**
    	 * 获取数据库链接的静态方法  这样子就保证了只加载一次文件的操作
    	 * @return
    	 * @throws Exception
    	 */
    	public static Connection getConn() throws Exception{
    
    		String jdbcDriver=null;
    		String url=null;
    		String user=null;
    		String password=null;
    		
    		Properties p=new Properties();
    		InputStream is=
    				JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
    		p.load(is);
    		
    		jdbcDriver=p.getProperty("jdbcDriver");
    		url=p.getProperty("url");
    		user=p.getProperty("user");
    		password=p.getProperty("password");
    		
    		Class.forName(jdbcDriver);
    		
    		return DriverManager.getConnection(url, user, password);
    	}
    

      

        其中  jdbc.properties  是属性配置文件,因为是通过  类名.class.getClassLoader().getResourceAsStream("jdbc.properties");获取的,所以

    该属性配置文件需要放置在src目录下。其内容的例子:

      jdbcDriver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/test
      user=root
      password=root

        接着是2)释放数据库链接资源

            /**
    	 * 关闭从数据库服务器等索取的资源:先关闭后获取的
    	 * @param conn
    	 * @param pstmt
    	 */
    	public static void closeResource(Connection conn,Statement stmt,ResultSet rs){
    		
    		if (rs != null) {
    			try {
    				rs.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		
    		if (stmt != null) {
    			try {
    				stmt.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		
    		if (conn != null) {
    			try {
    				conn.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	
        
    

       由于PreparedStatement是Statement的子接口,所以该方法也适合传入PreparedStatement的对象

      然后是3)数据库的更新操作,包括插入,删除,修改 

            /**
    	 * 统一的更新操作 Statement:insert update delete
    	 * @param conn
    	 * @param sql
    	 * @throws Exception
    	 */
    	public void update(String sql){
    		
    		Connection conn=null;
    		Statement stmt=null;
    		
    		try {
    			
    			conn=JDBCTools.getConn();
    			stmt=conn.createStatement();
    			stmt.executeUpdate(sql);
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally{
    			closeResource(conn, stmt, null);
    		}
    	}
    	
    	/**
    	 * 适用于PreparedStatment
    	 * @param sql
    	 * @param args
    	 */
    	public void update2(String sql,Object ... args){
    		Connection conn=null;
    		PreparedStatement pstmt=null;
    		ResultSet rs=null;
    		
    		try {
    			
    			conn=JDBCTools.getConn();
    			pstmt=conn.prepareStatement(sql);
    			
    			for(int i=0;i<args.length;i++){
    				pstmt.setObject(i+1, args[i]);
    			}
    			
    			pstmt.executeUpdate();
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally{
    			JDBCTools.closeResource(conn, pstmt, rs);
    		}
    	}        
    

       其中这段代码:for(int i=0;i<args.length;i++){ pstmt.setObject(i+1, args[i]); } 的意思在于:设置SQL语句中的占位符 ? 的值。

      最后是4)数据库的查询操作:在这里写了通用的方法,目的在于将查询得到的结果集封装在统一的实体中,这里采用了泛型,反射机制的知识

            /**
    	 * 泛型方法  反射机制  通用的查询方法存储实体
    	 * @param clazz
    	 * @param sql
    	 * @param args
    	 * @return
    	 */
    	public <T> T getT(Class<T> clazz,String sql,Object ... args){
    		T t=null;
    		
    		Connection conn=null;
    		PreparedStatement pstmt=null;
    		ResultSet rs=null;
    		
    		ResultSetMetaData rsmd=null;
    		
    		try {
    			
    			conn=JDBCTools.getConn();
    			pstmt=conn.prepareStatement(sql);
    			
    			for(int i=0;i<args.length;i++){
    				pstmt.setObject(i+1, args[i]);
    			}
    			
    			rs=pstmt.executeQuery();
    			
    			if (rs.next()) {
    				t=clazz.newInstance();
    				
    				Map<String, Object> map=new HashMap<String, Object>();
    				
    				//解析sql获取对象
    				rsmd = rs.getMetaData();
    				int numberOfColumns = rsmd.getColumnCount();
    				
    				for(int i=0;i<numberOfColumns;i++)
    				{
                            //获取列的名字,如果有别名,则获取的是别名 String columnName=rsmd.getColumnLabel(i+1); map.put(columnName, rs.getObject(columnName)); } if (map.size() > 0) { for(Map.Entry<String, Object> entry: map.entrySet()) { String columnName=entry.getKey(); Object columnValue=entry.getValue(); Field field = t.getClass().getDeclaredField(columnName); field.setAccessible(true); field.set(t, columnValue); } } } } catch (Exception e) { e.printStackTrace(); } finally{ JDBCTools.closeResource(conn, pstmt, rs); } return t; }
  • 相关阅读:
    SpringBoot自定义FailureAnalyzer
    Linux 系统目录结构
    Spring Boot实战:静态资源处理
    Activiti7整合SpringBoot(十二)
    Acvitivi网关(十一)
    为什么阿里巴巴要禁用Executors创建线程池?
    lqb 基础练习 数列排序 (sort的使用)
    lqb 入门训练 A+B问题
    lqb 入门训练 序列求和 (PS:用长整数做数据的输入输出)
    lqb 入门训练 圆的面积 (PS: PI的精确计算方法 atan(1.0) * 4)
  • 原文地址:https://www.cnblogs.com/SteadyJack/p/5255357.html
Copyright © 2020-2023  润新知