[英]how to display all the data from the database to jtable?
我们在数据库中有一个称为数据的表,我们想使用NetBeans IDE检索并显示JTable组件中的所有数据。 数据库中的每一行都应显示在jtable中。
另外,请记住,MVC是游戏的名称。 扩展AbstractTableModel以便创建一个将数据提供给JTable的模型。
您将需要实现以下方法:
public int getRowCount()
public int getColumnCount() and
public Object getValueAt(int rowIndex, int columnIndex)
最后将模型设置为JTable:
myJTable.setModel(new MyModel());
像这样:
public class MyModel extends AbstractTableModel {
private Connection con;
private Statement stmt;
private ResultSet rs;
public MyModel () {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename?useUnicode=true&characterEncoding=UTF-8",
"root", "password");
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("select * from tablename");
} catch (SQLException e) {
String msg = "MyModel(): Error Connecting to Database:\n"
+ e.getMessage();
System.out.println(msg);
}
} catch (ClassNotFoundException e) {
String msg = "The com.mysql.jdbc.Driver is missing\n"
+ "install and rerun the application";
System.out.println(msg);
System.exit(1);
} finally {
}
}
public int getRowCount() {
// count your rows and return
return count;
}
public int getColumnCount() {
// how many cols will you need goes here
return 3;
}
public Object getValueAt(int rowIndex, int columnIndex) {
try {
rs.absolute(rowIndex + 1);
switch (columnIndex) {
case 0:
return rs.getInt(1);
case 1:
return rs.getString(2);
case 2:
return rs.getString(6);
default:
return null;
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
}
您可以导入DbUtils并将其用于将数据库导入JTable,如下所示:
Class.forName("com.mysql.jdbc.Driver"); Connection connectionToDB = (Connection)DriverManager.getConnection(hostname, user,pw); PreparedStatement preparedStatement = connectionToDB.prepareStatement("SELECT * FROM Table;"); ResultSet resultSetForFullTable = preparedStatement.executeQuery(); dbTable.setModel(DbUtils.resultSetToTableModel(resultSetForFullTable));
import net.proteanit.sql.DbUtils;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.