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

    结果: 

  • 相关阅读:
    高级数据结构实现——自顶向下伸展树
    优先队列——二项队列(binominal queue)
    优先队列——左式堆
    近似装箱问题(两种脱机算法实现)
    近似装箱问题(三种联机算法实现)
    Instruments
    CALayer之 customizing timing of an animation
    PKCS填充方式
    使用Xcode和Instruments调试解决iOS内存泄露
    apple网址
  • 原文地址:https://www.cnblogs.com/hq233/p/6249854.html
Copyright © 2011-2022 走看看