java - 返回基于 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
。
解决方案
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 + "]");
}
}
推荐阅读
- mfc - 我的 HiDPI 显示器上的 Visual Studio MFC 对话框编辑器似乎坏了 - 这是一个已知问题吗?
- java - Hibernate vs Spring 连接获取策略
- c - 使用 pthread、互斥锁和条件变量解决哲学家就餐问题
- java - 访问子元素
- pojo类
- java - 当 JPanel 应该填充 JFrame 时,它周围有一点额外的空间
- angular - 我的角度服务在不同组件之间丢失了状态
- reactjs - 在反应中为常见状态创建一个钩子
- upgrade - Artifactory 升级失败 helm chart 7.18.3 到 8.4.7
- pyspark - 加入数组交点
- python - 如何在 PyQtGraph 中设置 GraphicsWindow 位置?