zoukankan      html  css  js  c++  java
  • JDBC MySQL 多表关联查询查询

    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)+"	");
                System.out.print(rs.getString(2)+"	");
                System.out.print(rs.getBoolean(3)?"男	":"女	"); //?:简单判断
                System.out.print(minzu(rs.getString(4))+"	");
                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);
        }

    结果: 

  • 相关阅读:
    剑指offer(45)扑克牌顺子
    剑指offer(44)单词翻转序列
    剑指offer(43)左旋转字符串
    剑指offer(42)和为S的字符串
    剑指offer(41)和为S的连续正数序列
    剑指offer(40)数组中只出现一次的数字
    剑指offer(39)平衡二叉树
    面试金典——字符串压缩
    LeetCode——恢复二叉搜索树
    LeetCode——修剪二叉搜索树
  • 原文地址:https://www.cnblogs.com/hq233/p/6249854.html
Copyright © 2011-2022 走看看