繁体   English   中英

如何将MySQL查询结果放到一个List中<string>在 java</string>

[英]How to get the MySQL query results into a List<String> in java

我有 SQL 查询,它产生多行和多列。
我想执行此查询并将结果放入List<String>而不是 ResultSet。

"select LectureDay, LectureStatus from lecturelist where LectureName like "Java%"; 
res = pstmt.executeQuery();

我想要List<String>中的查询结果

public static List<String> ResultList;

while 语句看起来像这样

    while(res.next())
            {
                String LectureStatus = res.getString("LectureStatus");
                String LectureDay = res.getString("LectureDay");
            }
            res.close();

代码:

public void GetData(){
String url = "jdbc:mysql://localhost/DB?serverTimezone=UTC";
String sql = "select LectureDay, LectureStatus from lecturelist where LectureName like 'Java%'";
pstmt = conn.prepareStatement(sql);
res = pstmt.executeQuery();
try 
        {           
            Class.forName(driver_name);
            conn = DriverManager.getConnection(url, user, password);
            pstmt = conn.prepareStatement(sql);
            while(res.next())
            {
                String LectureStatus = res.getString("LectureStatus");
                String LectureDay = res.getString("LectureDay");
            }
            res.close();
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }       
        finally {
                try {
                    pstmt.close();
                    conn.close();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
        }
    }
}

谢谢你读这个

    public void GetData(){
    String url = "jdbc:mysql://localhost/DB?serverTimezone=UTC";
    String sql = "select LectureDay, LectureStatus from lecturelist where LectureName like "Java%";
    pstmt = conn.prepareStatement(sql);
    res = pstmt.executeQuery();
    List<String> list = new ArrayList<>();
    try
    {
        Class.forName(driver_name);
        conn = DriverManager.getConnection(url, user, password);
        pstmt = conn.prepareStatement(sql);
        while(res.next())
        {
            String LectureStatus = res.getString("LectureStatus");
            String LectureDay = res.getString("LectureDay");
            list.add(LectureStatus);
            list.add(LectureDay);
        }
        res.close();
    catch (Exception e)
        {
            System.out.println(e.getMessage());
        }       
    finally {
        try {
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM