Home > Net >  How to get the MySQL query results into a List<String> in java
How to get the MySQL query results into a List<String> in java

Time:05-06

I have SQL query which results in multiple rows and columns.
I want to execute this query and get the results into List<String> instead of the ResultSet.

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

I want the results of the query in List<String>

public static List<String> ResultList;

while statements look like this

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

code:

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

thank u for read this

CodePudding user response:

    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());
        }
    }
    }
}
  • Related