gpt4 book ai didi

java - JTable 从 MySQL 数据库获取值

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:33 24 4
gpt4 key购买 nike

我需要从数据库中获取所有值并将其放入 JTable 中,填充所有行。我的代码只将最后一行放入 JTable 中,而错过了所有前面的内容。有人知道如何从数据库中获取所有值并将它们全部插入到 JTable 中吗?

try{
Class.forName("com.mysql.jdbc.Driver");
conn3 = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=123456");
stmt3 = conn3.createStatement();
rs3 = stmt3.executeQuery("SELECT * FROM teams");
String str1 = null,str2 = null,str3 = null,str4 = null,str5 = null;
while (rs3.next())
{
str1 = rs3.getString(1);
str2 = rs3.getString(2);
str3 = rs3.getString(3);
str4 = rs3.getString(4);
str5 = rs3.getString(5);
}

Object[][] data = {{str1,str2,str3,str4,str5}};
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(10, 321, 297, 143);
frame.getContentPane().add(table);
rs3.close();
stmt3.close();
conn3.close();
}
catch (SQLException se)
{
System.out.println( "SQL Exception:" );
while( se != null )
{
System.out.println( "State : " + se.getSQLState() );
System.out.println( "Message: " + se.getMessage() );
System.out.println( "Error : " + se.getErrorCode() );
se = se.getNextException();
}
}
catch (ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
}

最佳答案

while (rs3.next())
{
str1 = rs3.getString(1);
str2 = rs3.getString(2);
str3 = rs3.getString(3);
str4 = rs3.getString(4);
str5 = rs3.getString(5);
}

您正在一次又一次地覆盖相同的变量。您应该改用列表或数组。像这样的东西:

while (rs3.next())
{
//Given that all of your str are declared as List<String> strX = new List<String>();
str1.add(rs3.getString(1));
str2.add(rs3.getString(2));
str3.add(rs3.getString(3));
str4.add(rs3.getString(4));
str5.add(rs3.getString(5));
}

但要在表中插入 ResultSet,有 plenty of tutorials .


编辑:如果您不想使用表格模型,您可以更改数据检索的逻辑。您必须向表格提供一个矩阵[行][列]。你是哪几排?您的哪些专栏?

行是结果集的“下一个”,而列是 1 到 5。您需要知道那里有多少行(有点棘手):

if (rs3.next()) {
rs3.last();
int rows = rs3.getRow();
}
rs3.beforeFirst();

现在创建矩阵:

String[][] matrix = new String[rows][4]; //Your Object[][] data.

int index = 0;
while(rs3.next()){
matrix[i][0] = rs3.getString(1);
matrix[i][1] = rs3.getString(2);
matrix[i][2] = rs3.getString(3);
matrix[i][3] = rs3.getString(4);
matrix[i][4] = rs3.getString(5);
i++;
}
String[] columnNames = {"id","Name","Players","Point","Position" };
table = new JTable(matrix, columnNames);

有用 另一个有用的(但不是严格要求的)检索对象数据的方法是using customized mappings或更复杂的对象关系映射框架,如 Hibernate .

关于java - JTable 从 MySQL 数据库获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com