`

java连接数据库

阅读更多
public class DataSourceProvider {
	
  private static Logger logger = Logger.getLogger(DataSourceProvider.class);
  static Map<String,DataSource> dataSourceCache = new HashMap<String,DataSource>();
	
	
  public static synchronized DataSource getDataSource(String jdbcDriver, 
             String jdbcUsername, String jdbcPassword, String jdbcUrl) {
    String key = jdbcDriver+jdbcUsername+jdbcPassword+jdbcUrl;
    DataSource dataSource = dataSourceCache.get(key);
       if(dataSource == null) {
	   try {
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.setDriverClass(jdbcDriver);
				
		ds.setUser(jdbcUsername);
		ds.setPassword(jdbcPassword);
		ds.setJdbcUrl(jdbcUrl);
		ds.setCheckoutTimeout(10 * 1000);
				
		if(jdbcDriver.contains("mysql")) {
		    ds.setPreferredTestQuery("select 1");
		    ds.setIdleConnectionTestPeriod(60);
		}
		ds.setUnreturnedConnectionTimeout(60 * 60);
		ds.setLoginTimeout(10);
	
        dataSource = ds;
		dataSourceCache.put(key, dataSource);
		logger.info("create DataSource,url:["+jdbcUrl+"], username:"+jdbcUsername);
		} catch (PropertyVetoException e) {
		  throw new IllegalArgumentException("invalid driver:"+jdbcDriver,e);
		} catch( SQLException e) {
		    throw new IllegalArgumentException(e);
		}
		}
		return dataSource;
	}
}


 

public class TableUtil {

   private static Log logger = LogFactory.getLog(TableUtil.class);
	
   private static DsService dsService;
   private static TableInfoService tableInfoService;
	
   private static void init(){
     dsService = (DsService) ApplicationContextHolder.getBean("dsService");
     tableInfoService = (TableInfoService)ApplicationContextHolder.getBean("tableInfoService");
	}
	
   public static void refreshDbTables(){
      init();
		
      List<Ds> dataSources = dsService.getDsList();
      for (Ds ds:dataSources) {
			
      DataSource dataSource = DataSourceProvider.getDataSource(ds.getDriver(), 
                           ds.getUsername(), ds.getPassword(), ds.getUrl());
			
      //jdbc:mysql://183.61.12.73:3306/lobbystat3?useUnicode=true&characterEncoding=utf8
      //截取库名
      String url = ds.getUrl();
      String database = url.substring(url.lastIndexOf("/")+1, url.indexOf("?"));
			
       Map<String, String> tableInfoMap = getDbTableInfo(dataSource, database);
       for(Map.Entry<String, String> tableInfo:tableInfoMap.entrySet()){
	  logger.info("====>添加表:"+database+"."+tableInfo.getKey());
	  logger.info("====>"+tableInfo.getValue());
	    TableInfo tableInfoEntity = new TableInfo(tableInfo.getKey(), database, 
                           tableInfo.getValue());
	    tableInfoService.addTableInfo(tableInfoEntity);
             logger.info("====>添加完毕:"+database+"."+tableInfo.getKey());
	}
			
		}
		
	}
	
	
	/**
	 * 把某一个库的表信息保存到Map<String, String>里==>Map<表名, 建表信息>
	 * @param dataSource
	 * @param database
	 * @return
	 */
	public static Map<String, String> getDbTableInfo(DataSource dataSource,
                                        String database){
	   Map<String, String> tableMap = new HashMap<String, String>();
	   NamedParameterJdbcTemplate dataSourceJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	    String tableSql = "show tables from " + database;
	    List<String> tables = dataSourceJdbcTemplate.getJdbcOperations().queryForList(tableSql, String.class);
	    for(String table:tables){
		String createInfoSql = "SHOW CREATE TABLE " + table;
	        Map<String, Object> resultMap = dataSourceJdbcTemplate.getJdbcOperations().queryForMap(createInfoSql);
		String createInfo = (String) resultMap.get("Create Table") !=null ? (String) resultMap.get("Create Table") : (String) resultMap.get("Create View");
		tableMap.put(table, createInfo);
		}
	  return tableMap;
	}

    

    参考:http://286.iteye.com/blog/1920417

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics