廢話不錯說直接上代碼
1 package Jdbc01; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.ResultSetMetaData; 8 9 /* 10 * 測試ResultSet獲得SQL查詢結果 11 * SQL語句: select * from student 12 */ 13 public class Demo4 { 14 public static void main(String[] args){ 15 Connection conn = null; 16 PreparedStatement ps = null; 17 ResultSet rs = null; 18 19 try { 20 //注冊類 21 Class.forName("com.mysql.cj.jdbc.Driver"); 22 //建立連接 23 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testJDBC?characterEncoding=utf8","root","shmily"); 24 //查詢語句 25 String sql1 = "select * from student"; 26 ps = conn.prepareStatement(sql1); 27 rs = ps.executeQuery(); 28 //獲取列數 29 ResultSetMetaData md= rs.getMetaData(); 30 int columnSize = md.getColumnCount(); 31 32 System.out.println("查詢結果如下:"); 33 //打印字段名 34 for(int i = 1; i <= columnSize; i++){ 35 System.out.printf("%-12s",md.getColumnName(i)); 36 } 37 System.out.println(); 38 //打印所有記錄 39 while(rs.next()) { 40 for(int i = 1; i <= columnSize ; i++){ 41 System.out.printf("%-12s",rs.getObject(i)); 42 } 43 System.out.println(); 44 } 45 System.out.println("\n結束查詢"); 46 47 } catch (ClassNotFoundException e) { 48 e.printStackTrace(); 49 } catch (Exception e) { 50 e.printStackTrace(); 51 } finally { 52 //關閉順序: ResultSet-->Statement-->Connection 53 try { 54 if(rs!=null) { 55 rs.close(); 56 } 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } 60 try { 61 if(ps!=null) { 62 ps.close(); 63 } 64 } catch (Exception e) { 65 e.printStackTrace(); 66 } 67 try { 68 if(conn!=null) { 69 conn.close(); 70 } 71 } catch (Exception e) { 72 e.printStackTrace(); 73 } 74 } 75 76 } 77 }
查詢結果如下: id Name Age regTime 1 韓梅梅 15 2019-06-17 2 李雷 15 2019-06-19 4 趙靈兒 14 2019-06-19 結束查詢
最后請教一下如何讓所有記錄完美對齊?