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();
- }
- }
- }