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);
}
结果: