結果: ...
public static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root",""); String sql ="select * from info"; //關聯查詢時,可以直接join on.但是效率不高 //String sql ="select info.Code,info.Name,info.Sex,nation.Name sb ,info.Birthday from info join nation on info.Nation=nation.Code "; Statement state = conn.createStatement(); ResultSet rs = state.executeQuery(sql); while(rs.next()){//判斷是否還有下一行 System.out.print(rs.getString(1)+"\t"); System.out.print(rs.getString(2)+"\t"); System.out.print(rs.getBoolean(3)?"男\t":"女\t"); //?:簡單判斷 System.out.print(minzu(rs.getString(4))+"\t"); System.out.println(bianhuan(rs.getDate(5))); } conn.close(); } //關聯查詢時,也能寫個方法再查一遍另一個表,然後賦給原來的列 private static String minzu(String m)throws Exception { String mz= "";//定義空字元串 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb","root",""); Statement sta = conn.createStatement(); String sql = "select * from nation where code = '"+m+"'"; ResultSet rs = sta.executeQuery(sql); if(rs.next() == true){ //有對應的sql語句的時候,才執行 mz = rs.getString(2);//另一個表的的列賦值給mz } conn.close(); return mz; //返回mz } //日期時間轉換 public static String bianhuan(Date d){ SimpleDateFormat f = new SimpleDateFormat("yyyy年mm月dd日"); return f.format(d); }
結果: