[英]Storing data from MySQL into multi-dimensional array?
我正在嘗試存儲從MySQL數據庫表調用的數據,其中數據將基於特定的用戶編號。 我已經使用PreparedStatement
和ResultSet
設置了連接。 通過使用while loop
,我需要從數據庫中調用數據並將其存儲在此數組中。 存儲后,我需要在數組中調用此數據以顯示在界面上的文本字段中。
這是代碼:
public static void find(int x)
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","root");
PreparedStatement stmt=conn.PrepareStatement("Select * from employee where userNum ='" + x +"'");
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
}
我試圖在while loop
中放入一些語句,以顯示從數組到接口的數據。
而不是使用字符串串聯將x值獲取到查詢中,而是放置一個?
在字符串中,然后使用setInt(1, x)
函數設置要替換查詢的值。 索引從1開始。
為了在通過列表后僅要獲取行數以初始化2D數組之后使用first()
,必須將結果設置為TYPE_SCROLL_INSENSITIVE
。 為每個列獲取特定類型而不是僅僅將所有內容都視為一個對象可能會更好。 但是,如果有用的話,就可以做到。
PreparedStatement stmt = conn.prepareStatement("Select * from employee where userNum=?",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE
);
stmt.setInt(1, x);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
List l = new ArrayList();
rs.first();
int rowcount = 0;
do {
rowcount++;
} while (rs.next());
rs.first();
int rowindex = 0;
Object array2D[][] = new Object[rowcount][];
do {
array2D[rowindex] = new Object[numberOfColumns];
for (int i = 0; i < numberOfColumns; i++) {
array2D[rowindex][i] = rs.getObject(i + 1);
}
// prints each row on separate line
System.out.println("array2D[" + rowindex + "] = " + Arrays.toString(array2D[rowindex]));
rowindex++;
} while (rs.next());
System.out.println("array2D = " + Arrays.deepToString(array2D));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.