首页 > 解决方案 > 返回基于 SQL 的动态数组

问题描述

我想创建一个方法,该方法返回一个包含数据库中所有值的数组。

这是我到目前为止所拥有的:

package ch.test.zt;

import java.sql.*;

class Database {

    static boolean getData(String sql) {
        // Ensure we have mariadb Driver in classpath
        try {
            Class.forName("org.mariadb.jdbc.Driver");
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:mariadb://localhost:3306/zt_productions?user=root&password=test";

        try {
            Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            return rs.next();

        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

}

这意味着,我可以使用Database.getData("SELECT * FROM users")并获得一个数组,其中包含我需要的数据库中的所有数据。

在我上面的代码中,我使用return rs.next();的是 ,这绝对是错误的。那返回true

标签: javajdbc

解决方案


rs.next(); just tell whether your result set has data in it or not i.e true or false , in order to use or create array of the actual data , you have to iterate over your result set and create a user object from it and have to add that object in your users list

Also change the signature

 static List<User> getData(String sql) 

And best to use like Select Username,UserId from Users; as your sql something like this:

   try {    List<User> userList = new ArrayLisy();
            Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            //until there are results in the resultset loop over it
             while (rs.next()) {              
               User user = new User();
               user.SetName(rs.getString("username"));
               // so on.. for other fields like userID ,age , gender ,loginDate,isActive  etc ..
               userList.add(user);
            } 
          }

when you don't know about the columns of the table you are going to fetch then you can find the same using :

Now you know all the information then you can construct a proper query using it and work from this

  DatabaseMetaData metadata = connection.getMetaData();
        ResultSet resultSet = metadata.getColumns(null, null, "users", null);
        while (resultSet.next()) {
          String name = resultSet.getString("COLUMN_NAME");
          String type = resultSet.getString("TYPE_NAME");
          int size = resultSet.getInt("COLUMN_SIZE");

          System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
        }
      }       

推荐阅读