JDBC MySQL 多表關聯查詢查詢

來源:互聯網
上載者:User

標籤:void   static   info   string   cut   select   str   throws   stat   

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= "";//定義Null 字元串        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);    }

結果: 

 

JDBC MySQL 多表關聯查詢查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.