獲取數據庫所有表名,返回json串

       /**
	 * 獲得數據庫所有表名
	 */
	@Override
	public JSONArray getTableNameForForeign() {
		//獲取當前數據鏈接
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
               Session session = sessionFactory.getCurrentSession();
               Connection conn = session.connection();
        
		PreparedStatement pst = null;
		ResultSet rs = null;
		JSONArray jsonArr = new JSONArray();		
		String sql = "SHOW TABLES";
		
		try {
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while(rs.next()){
				TableNameBean table = new TableNameBean();
				String tableName = rs.getString(1);
				if(null != tableName && "zq_".equals(tableName.substring(0,3))){
					table.setTableNameId(ChangeUTF_16.deUnicode(tableName.substring(3)));
					table.setTableName(ChangeUTF_16.deUnicode(tableName.substring(3)));
					jsonArr.add(table);
				}
			}
			System.out.println(jsonArr.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {  
			 if(rs != null){
			    	try {
			    		rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					} finally{
						rs = null;
					}
			    }
		    if(pst != null){
		    	try {
					pst.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally{
					pst = null;
				}
		    }
		    if(conn != null){
		    	try {
		    		conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				} finally{
					conn = null;
				}
		    }
		}


		return jsonArr;	
	}

BEAN:
public class TableNameBean {
	String tableNameId;
	String tableName;
	public String getTableNameId() {
		return tableNameId;
	}

	public void setTableNameId(String tableNameId) {
		this.tableNameId = tableNameId;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

}
結果:[{"tableName":"goods","tableNameId":"goods"},{"tableName":"person","tableNameId":"person"}]

發佈了14 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章