jdbcTemplate 查询数据库字段名称,类型方法

jdbcTemplate 操作方法


/**
*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 fieldMap = new HashMap();
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 = https://www.it610.com/article/(ResultSetMetaData) result.getMetaData();
List metadataList = new ArrayList();
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 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();
}

}

}

    推荐阅读