import javasqlDriverManager;
import javasqlPreparedStatement;
import javasqlResultSet;
import javasqlSQLException;
import javautilLinkedList;
import javautilList;
public class DataToArray {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/test";// 改成你的数据库连接
Connection conn = DriverManagergetConnection(url, "root", "fuhaiwei");// 改成你用户名密码
String sql = "select from user";// 改成你的查询语句
PreparedStatement prestmt = connprepareStatement(sql);
ResultSet rs = prestmtexecuteQuery();
Object[][] data = getDataArray(rs);
printArray(data);
rsclose();
prestmtclose();
connclose();
}
private static void printArray(Object[][] data) {
for (int i = 0; i < datalength; i++) {
for (int j = 0; j < data[i]length; j++) {
Systemoutprint(data[i][j] + " ");
}
Systemoutprintln();
}
}
private static Object[][] getDataArray(ResultSet rs) throws SQLException {
List<Object[]> list = new LinkedList();
while (rsnext()) {
// 改成你的列名
Object[] objects = new Object[] { rsgetInt("id"), rsgetString("username"),
rsgetString("password") };
listadd(objects);
}
return listtoArray(new Object[0][0]);
}
}
输出效果:
一个表里的某条数据还是一个表里某个字段下所有的数据?看看是不是你要的效果。
public class TestColumnToArray {
public static void main(String[] args) {
TestColumnToArray instance = new TestColumnToArray();
instanceconnDB();
List<Map<String, Object>> list = instancefindColumn();
Object[] data = instancegetData(list, "。。。");//。。。换成要查得字段
for (Object object : data) {
Systemoutprintln(object);
}
}
private Object[] getData(List<Map<String, Object>> list, String column) {
Object[] data = new Object[listsize()];
for (int i = 0; i < listsize(); i++) {
data[i] = listget(i)get(column);
}
return data;
}
private void connDB() {
try {
ClassforName("commysqljdbcDriver");
} catch (ClassNotFoundException e) {
Systemerrprintln("驱动加载失败!");
}
}
private List<Map<String, Object>> findColumn() {
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "select from 。。。";//。。。换成表名
try {
conn = DriverManagergetConnection("。", "。。", "。。。");//。换成url。。换成数据库账户。。。换成数据库密码
stmt = conncreateStatement();
rs = stmtexecuteQuery(sql);
while (rsnext()) {
Map<String, Object> map = new HashMap<String, Object>();
mapput("。。。", rsgetInt(1));//。。。换成列名
mapput("。。。", rsgetInt(2));
mapput("。。。", rsgetInt(3));
listadd(map);
}
} catch (SQLException e) {
Systemerrprintln("数据库读取失败!");
} finally {
try {
if (rs != null) rsclose();
if (stmt != null) stmtclose();
if (conn != null) connclose();
} catch (SQLException e) {}
}
return list;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)