在 Java 中使用 JTable 显示 MySQL 数据库中的记录
Posted
技术标签:
【中文标题】在 Java 中使用 JTable 显示 MySQL 数据库中的记录【英文标题】:Display Records From MySQL Database using JTable in Java 【发布时间】:2014-02-20 04:20:35 【问题描述】:我想从 mysql 数据库将 JTable
连接到 ResultSet
,以便查看数据。
我正在寻找一些描述此任务的链接或代码 sn-ps。我正在使用 Netbeans IDE..
【问题讨论】:
看到这个问题:***.com/questions/10620448/… 或这个问题***.com/questions/7620492/… 这个问答(***.com/questions/10620448/…)可能会解决你的问题 这个问题似乎是题外话,因为它是关于如何做某事而不显示任何尝试或努力来实现所要求的。这种格式的问题不遵循关于可以在 SO 中提出的主题的指南。见***.com/help/on-topic 【参考方案1】:下面是一个类,它将完成您在将数据从 MySQL 数据库读取到 Java 中的 JTable
时想要执行的基本操作。
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
public TableFromMySqlDatabase()
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
columnNames.add( md.getColumnName(i) );
// Get row data
while (rs.next())
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
row.add( rs.getObject(i) );
data.add( row );
catch (SQLException e)
System.out.println( e.getMessage() );
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
subVector.add(subArray.get(j));
dataVector.add(subVector);
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
public Class getColumnClass(int column)
for (int row = 0; row < getRowCount(); row++)
Object o = getValueAt(row, column);
if (o != null)
return o.getClass();
return Object.class;
;
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
public static void main(String[] args)
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
在您使用的 NetBeans IDE 中 - 您需要在项目属性中添加 MySQL JDBC 驱动程序,如下所示:
否则代码将抛出一个SQLException
说明找不到驱动程序。
现在在我的示例中,yourdb
是数据库的名称,animals
是我正在执行查询的表的名称。
以下是输出内容:
离别说明:
您说您是新手,需要一些帮助来理解 Java 的一些基本类和概念。我将在这里列出一些,但请记住,您可以随时浏览 Oracle 网站上的文档。
ArrayList Vector Try-with-resources statement【讨论】:
感谢您的回复,但我需要简短易懂的示例代码... 我已经使用来自同一个网站的示例代码进行了更新。 什么是矢量??对不起,我只是一个初学者。 我已经更新了我的答案,其中包含一个解释Vector
类的教程的链接。 Vector
类被认为已弃用,并且主要出现在遗留代码中 - 将改用 ArrayList
类,但代码仍然可以工作。
我已经修改了我的答案,回复应该非常适合您的需求。让我知道它是否对您有帮助。【参考方案2】:
这是一种简单的方法,您只需下载 jar 文件 "rs2xml.jar"
将其添加到您的项目中
并这样做:
1-创建连接
2- 语句和结果集
3-创建一个jtable
4-将结果集提供给DbUtils.resultSetToTableModel(rs)
正如在这个方法中定义的那样,你很容易得到你的 jtable。
public void afficherAll(String tableName)
String sql="select * from "+tableName;
try
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
catch (SQLException e)
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e);
【讨论】:
【参考方案3】:如果您需要在代码中大量使用数据库并且您知道表的结构,我建议您按照以下方式进行操作:
首先,您可以定义一个类,该类将帮助您制作能够保存表格行数据的对象。例如,在我的项目中,我创建了一个名为 Document.java 的类来保存数据库中单个文档的数据,并制作了这些对象的数组列表来保存我的表的数据,该数据由查询。
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* @author Administrator
*/
public class Document
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna)
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
public Document(int dn,boolean dt,boolean ds, long dpa)
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
// Print document information
public void printDocumentInformation ()
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
其次,您可以定义一个类来处理您的数据库需求。例如,我定义了一个名为 DataBase.java 的类,它处理我与数据库的连接以及我需要的查询。我在我的主类中实例化了一个反对它。
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class DataBase
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase()
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
/**
* Set variables and objects for this class.
*/
private void Initialize()
System.out.println("Loading driver...");
try
Class.forName(driver);
System.out.println("Driver loaded!");
catch (ClassNotFoundException e)
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password))
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
catch (SQLException e)
throw new IllegalStateException("Cannot connect the database!", e);
/**
* Write Queries
* @param s
* @return
*/
public boolean insertQuery(String s)
boolean ret = false;
System.out.println("Loading driver...");
try
Class.forName(driver);
System.out.println("Driver loaded!");
catch (ClassNotFoundException e)
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password))
System.out.println("Database connected!");
//Set tables' information
try
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1)
System.out.print("Successfully inserted value");
ret = true;
else
System.out.print("Unsuccessful insertion");
ret = false;
st.close();
catch (SQLException ex)
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
connect.close();
catch (SQLException e)
throw new IllegalStateException("Cannot connect the database!", e);
return ret;
/**
* Query needed to get code table's data
* @param c
* @return
*/
private void selectCodeTableQueryArray(Connection c)
try
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next())
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
st.close();
catch (SQLException ex)
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
private void printCodeTableQueryArray()
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectActivityTableQueryArray(Connection c)
try
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next())
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
st.close();
catch (SQLException ex)
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
private void printActivityTableQueryArray()
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
/**
* Query needed to get client table's data
* @param c
* @return
*/
private void selectClientTableQueryArray(Connection c)
try
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next())
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
st.close();
catch (SQLException ex)
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
private void printClientTableQueryArray()
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
/**
* Query needed to get activity table's data
* @param c
* @return
*/
private void selectEmployeeTableQueryArray(Connection c)
try
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next())
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
st.close();
catch (SQLException ex)
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
private void printEmployeeTableQueryArray()
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
我希望这可以提供一点帮助。
【讨论】:
以上是关于在 Java 中使用 JTable 显示 MySQL 数据库中的记录的主要内容,如果未能解决你的问题,请参考以下文章