您好,我已经成功地将我的 jTable 链接到 JDBC 数据库。 但是,我无法检索它们。我希望在重新启动程序时显示保存的数据,但它不起作用。
alarm.setText("");
DefaultTableModel model =(DefaultTableModel) hwList.getModel();
if(!className.getText().trim().equals(""))
{
model.addRow(new Object[]{className.getText(), homeWork.getText(), dueDate.getText()});
}
else
{
alarm.setText("Class Name should not be blank.");
}
Connection conn;
Statement st;
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/mysql";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
System.out.println("Connected to databse");
String a = className.getText();
String b = homeWork.getText();
String c = dueDate.getText();
System.out.println("Inserting into the table");
st = conn.createStatement();
String stmt="INSERT INTO hwList (className, homeWork, dueDate)"+ "VALUES ("+"\'"+a+"\',"+"\'"+b+"\',"+"\'"+c+"\')";
System.out.println(stmt);
st.executeUpdate(stmt);
System.out.println("Saved!");
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
这是我保存文档的代码!
有什么方法可以从JDBC数据库中获取数据并通过Jtable显示出来吗? 很抱歉问了这么简单的问题,但我是 Java 的新手,我迫切需要帮助!
非常感谢!
用于加载数据的代码...
顺便说一句,我的 jtable 是一个包含三列的 3 列表——分别是 className、homeWork、dueDate。 谢谢!
String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
String d = rs.getString("className");
String e = rs.getString("homeWork");
String f = rs.getString("dueDate");
}
最佳答案
首先创建一个新的 TableModel
...
DefaultTableModel model = new DefaultTableModel(new String[]{"Class Name", "Home work", "Due Date"}, 0);
从数据库中加载数据...
String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);
将每一行数据添加到表模型...
while(rs.next())
{
String d = rs.getString("className");
String e = rs.getString("homeWork");
String f = rs.getString("dueDate");
model.addRow(new Object[]{d, e, f});
}
将模型应用于您的 JTable
...
table.setModel(model);
您可能还想看看 The try-with-resources Statement并确保您正确管理资源
关于java - 从 JDBC 数据库中检索数据到 Jtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815400/