1. 程式人生 > 其它 >IDEA操作資料庫--查詢多行結果

IDEA操作資料庫--查詢多行結果

IDEA操作資料庫--查詢多行結果

import java.sql.*;

/**
 * @ClassName PrintUsers
 * @Description
 **/
public class PrintUsers {
    String sql = "SELECT LOGIN_NAME,GENDER,PHONE FROM SYS_BSE_USER ORDER BY USER_ID_KEY DESC ;";//查詢一個使用者資訊

    public void runSql() {
        //連線、操作資料庫主要用到如下幾個類。
        Connection con = null
;//資料庫連線類,用於連線資料庫 Statement st = null;//用於執行資料庫的CRUD語句 ResultSet rs = null;//用於接收資料庫SELECT語句的查詢結果,並對結果進行操作 try { con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName= GROWING_DB", "grow_update", "123456"); //DriverManager類管理很多資料庫驅動,getConnection方法是根據給定的資料庫連線字串和使用者名稱、密碼去連線資料庫
//這個連線字串各個資料庫有不用的寫法:例如pg庫的連線字串就是jdbc:sqlserver://localhost:1433/GROWING_DB System.out.println("資料庫連線成功"); try { st = con.createStatement(); rs = st.executeQuery(sql); System.out.println("使用者名稱 |"+"性別|"+"電話號碼"); while
(rs.next()) {//用while順序讀出多行資料 System.out.println(rs.getString("LOGIN_NAME") + " |" + rs.getString("GENDER") + " |" + rs.getString("PHONE")); //根據列名獲取值 } //rs.get***()系列方法是根據列行數,或列名讀取資料出來 } catch (SQLException e) { e.getStackTrace(); }finally { try{ if(st != null){ st.close(); } }catch (SQLException e){ e.getStackTrace(); } } } catch (SQLException e) { e.getStackTrace(); } finally{ try{ if(con != null){ con.close(); } }catch (SQLException e){ e.getStackTrace(); } } } }