gpt4 book ai didi

java - 从 sqliite 数据库获取的数据将单行的多个实例返回到 JTable

转载 作者:行者123 更新时间:2023-12-01 09:56:27 25 4
gpt4 key购买 nike

我尝试使用通过此代码从 Sqlite 数据库表获取的数据填充 JTable。

类 UserRecords 扩展 JPanel {

private static final long serialVersionUID = 6596285522176538665L;

String record_holderName=null;
public UserRecords(){}

public UserRecords(String name) {
this.record_holderName=name;

Connection con = null;
PreparedStatement st=null;
ResultSet rs=null;
JTable myTable = new JTable();


try {
con = ConnectDb.getDbConnection();
st=con.prepareStatement("select email,password,servicename,accounttype,hint,lastupdtime from usergems where record_holder=?");
st.setString(1,record_holderName);
rs = st.executeQuery();
ResultSetMetaData md= rs.getMetaData();
int columns=md.getColumnCount(); //holds number of column in resultSet

DefaultTableModel model= new DefaultTableModel(); //this object pass data into JTables

Vector<Object>columns_name=new Vector<Object>();
Vector<Object>data_rows=new Vector<Object>();

for(int i=1;i<columns;i++)
{
columns_name.addElement(md.getColumnName(i));
}
model.setColumnIdentifiers(columns_name);

while(rs.next())
{
for(int j=1;j<columns;j++)
{
data_rows.addElement(rs.getString(j));
}
model.addRow(data_rows);
}

myTable.setModel(model);

} catch(Exception e){
String msg = "ClassNotFoundException: Not able to load the db drivers\n Details: \n" + e;
JOptionPane.showMessageDialog(this, msg, "Error!", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}finally{
try{
rs.close();
st.close();
con.close();
}catch(Exception e){
JOptionPane.showConfirmDialog(null, e);
}
}

add(myTable);
myTable.setPreferredScrollableViewportSize(new Dimension(800,500));
JScrollPane pane =new JScrollPane(myTable);
add(pane,BorderLayout.CENTER );/*myTable.getRowHeight()* myTable.getRowCount())*/
//myTable.repaint();

}

}

这执行得很好,但只从数据库返回一行,多次(与数据库中的行数相同)这是结果和数据库表的屏幕截图。 Database result(data fetched)

请帮忙..

最佳答案

but returns only one row from the database,multiple time

因为你只有一个单行 vector 。

每行数据都需要一个新的 vector :

    while(rs.next())
{
Vector<Object> row = new Vector<Object>();

for(int j=1;j<columns;j++)
{
rows.addElement(rs.getString(j));
}

model.addRow(row);
}

关于java - 从 sqliite 数据库获取的数据将单行的多个实例返回到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170354/

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