import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DBSelect {
public static List<String[]> select(String sql, Object... params) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<String> setMethods = new ArrayList<>();
ResultSetMetaData metaData;
int columnCount = 0;
List<String[]> list = new ArrayList<String[]>();
// 获取数据
try {
conn = DBUtil.getConn();
ps = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
}
// 把列名放入集合
try {
metaData = rs.getMetaData();
columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
setMethods.add(metaData.getColumnName(i));
}
} catch (SQLException e) {
e.printStackTrace();
}
// 把数据放入集合
try {
while (rs.next()) {
String[] str = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
List<String> string = setMethods;
Object empno = rs.getObject(setMethods.get(i).toString().toLowerCase());
str[i] = empno + "";
}
list.add(str);
}
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.close(conn, ps, rs);
return list;
}
}
mysql查询方法
最新推荐文章于 2023-11-18 10:50:18 发布