jdbcTemplate 获取数据表结构
jdbcTemplate 操作方法
下面这里是JDBC的操作方法
- /**
- *1.方法一:
- */
- String sql = "select * from "+ tableName;
- //RowCountCallbackHandler rcch = new RowCountCallbackHandler();
- //this.jdbcTemplateDao.query(sql, rcch);
- //String[] coloumnName = rcch.getColumnNames();
- //int[] coloumnType = rcch.getColumnTypes();
- SqlRowSet sqlRowSet = this.jdbcTemplateDao.queryForRowSet(sql);
- SqlRowSetMetaData sqlRsmd = sqlRowSet.getMetaData();
- int columnCount = sqlRsmd.getColumnCount();
- for (int i = 1; i <= columnCount; i++) {
- Map<String,String> fieldMap = new HashMap<String,String>();
- fieldMap.put("name", sqlRsmd.getColumnName(i));
- fieldMap.put("fieldType", String.valueOf(sqlRsmd.getColumnType(i)));
- tableFieldList.add(fieldMap);
- }
- /**
- *方法二:
- */
- String sql = "select * from "+ tableName;
- RowCountCallbackHandler rcch = new RowCountCallbackHandler();
- this.jdbcTemplateDao.query(sql, rcch);
- String[] coloumnName = rcch.getColumnNames();
- int[] coloumnType = rcch.getColumnTypes();
下面这里是JDBC的操作方法
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.ResultSetMetaData;
- public class OperateDB {
- public static void main(String[] args) {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://192.168.11.211/education?useUnicode=true&characterEncoding=utf-8";
- String user = "root";
- String password = "12345678";
- Connection con = (Connection) DriverManager.getConnection(url, user, password);
- Statement statement = con.createStatement();
- ResultSet result = statement.executeQuery("select * from t_sys_user");
- 注意,这里,完全可以操作视图,操作表的sql语句 与操作视图的sql语句一样,
- ResultSetMetaData metadata = (ResultSetMetaData) result.getMetaData();
- List<String> metadataList = new ArrayList<String>();
- System.out.println("====================表结构=============================");
- for(int i = 1; i <= metadata.getColumnCount();i++){
- metadataList.add(metadata.getColumnName(i));
- System.out.print(metadata.getColumnName(i) + " "); //name
- System.out.print(metadata.getColumnTypeName(i) + " "); //type
- System.out.print(metadata.isNullable(i) + " "); //null
- System.out.print(metadata.getColumnCharacterSet(i) + " "); //encode
- System.out.println(); //key
- }
- System.out.println("====================表数据=============================");
- Iterator<String> i = null;
- String oneKey = null;
- while(result.next()){
- i = metadataList.iterator();
- while(i.hasNext()){
- oneKey = i.next();
- System.out.print(oneKey + ":" + result.getString(oneKey) + " ");
- }
- System.out.println();
- }
- result.close();
- statement.close();
- con.close();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
posted on 2016-03-02 08:40 nickTimer 阅读(2022) 评论(0) 编辑 收藏 举报