Obtain database metadata through JDBC's DatabaseMetaData

Original address: http://blog.csdn.net/hu_shengyang/article/details/7861261

package com.adam.test.entity;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.adam.dev.utils.JdbcByPropertiesUtil;

public class TestDatabaseMetaData {
	private JdbcByPropertiesUtil jbpu = JdbcByPropertiesUtil.getInstance();
	
	public JdbcByPropertiesUtil getJbpu() {
		return jbpu;
	}
	
	public void setJbpu(JdbcByPropertiesUtil jbpu){
		this.jbpu = jbpu;
	}
	
	public Properties getProperties(){
		Properties pros = JdbcByPropertiesUtil.readPropertiesFile();
		return pros;
	}

	/**
	 * Read the database name in the configuration file jdbc.properties
	 * @return
	 * @throws Exception
	 */
	public String getDataSourceName()throws Exception{
		Properties pros = this.getProperties();
		String dbName = pros.get("dbName").toString();
		return dbName;
	}
	
	/**
	 * Get the table name and view name in the database
	 * @return
	 */
	public List getTablesAndViews()throws Exception{
		Connection conn = jbpu.getConnection();
		ResultSet rs = null;
		List list = new ArrayList();
		try {
			Properties pros = this.getProperties();
			String schema = pros.get("user").toString();
			DatabaseMetaData metaData = conn.getMetaData();
			rs = metaData.getTables(null, schema, null, new String[]{"TABLE","VIEW"});
			while(rs.next()){
				String tableName = rs.getString("TABLE_NAME");
				list.add(tableName);
			}
		} catch (SQLException e) {
			e.printStackTrace ();
		} finally{
			jbpu.close(rs, null, conn);
		}
		return list;
	}
	
	/**
	 * Use the table name and database user name to query the field type corresponding to the table
	 * @param tableName table name
	 * @return
	 * @throws Exception
	 */
	public String generateBean()throws Exception{
		Connection conn = jbpu.getConnection();
		ResultSet rs = null;
		String strJavaBean = "";
		String tableName = this.getDataSourceName();
		try{
			Properties pros = this.getProperties();
			String schema = pros.get("user").toString();
			DatabaseMetaData metaData = conn.getMetaData();
			rs = metaData.getColumns(null, schema, tableName, null);
			Map map = new HashMap();
			while(rs.next()){
				String columnName = rs.getString("COLUMN_NAME");//列名
				String dataType = rs.getString("DATA_TYPE");//Field data type (corresponding to constants in java.sql.Types)
				String typeName = rs.getString("TYPE_NAME");//Field type name (for example: VACHAR2)
				map.put(columnName, dataType+":"+typeName);
			}
			
			// Other operations related to generating javaBeans
			
		}catch(Exception e){
			e.printStackTrace ();
		}finally{
			jbpu.close(rs, null, conn);
		}
		return strJavaBean;
	}
	
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326047725&siteId=291194637