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

    结果: 

  • 相关阅读:
    JSP--------------------图书管理器
    Vue-router的基本使用(创建--动态跳转)
    JSP邮箱小案例(完成全部功能)
    Vue CLI3脚手架的使用
    Vue小案例测试-------------------实现购物车小模块
    JSP第六次作业提交~~~~~~~~~~~~~~~~~~~~~
    JSP项目第二阶段(使用数据库存储与注册)
    jsp第三次作业-------------------------------
    2021/4/19作业
    4.12作业
  • 原文地址:https://www.cnblogs.com/hq233/p/6249854.html
Copyright © 2011-2022 走看看