jtable mysql数据库_使用Java中的JTable从MySQL数据库显示记录

bd96500e110b49cbb3cd949968f18be7.png

I want to connect a JTable to a ResultSet from a MySQL database so I can view the data.

I am looking for some links or code snippets describing this task. I'm using the Netbeans IDE..

解决方案

Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.

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);

}

}

In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:

shQUy.png

Otherwise the code will throw an SQLException stating that the driver cannot be found.

Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.

Here is what will be output:

QAz5f.png

Parting note:

You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了在Java Swing的JTable显示MySQL数据库记录,你需要执行以下步骤: 1. 连接到MySQL数据库使用JDBC API连接到MySQL数据库。你需要提供MySQL数据库的URL、用户名和密码。 2. 准备SQL查询:使用SQL查询语句从MySQL数据库检索数据。 3. 执行SQL查询:执行SQL查询并将结果存储在ResultSet对象。 4. 创建TableModel:TableModel是JTable显示数据的核心。你需要从ResultSet对象检索列名和数据,并创建一个DefaultTableModel对象。 5. 创建JTable使用DefaultTableModel对象创建JTable对象。 6. 添加JTable到JFrame:将JTable对象添加到JFrame。 下面是一个示例代码,它演示了如何在Java Swing的JTable显示MySQL数据库记录: ```java import java.sql.*; import javax.swing.*; import javax.swing.table.*; public class MySQLJTableExample extends JFrame { private JTable table; public MySQLJTableExample() { setTitle("MySQL JTable Example"); setSize(500, 500); setDefaultCloseOperation(EXIT_ON_CLOSE); // 连接到MySQL数据库 String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "mypassword"; String query = "SELECT * FROM mytable"; try (Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) { // 创建TableModel DefaultTableModel tableModel = new DefaultTableModel(); ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { tableModel.addColumn(metaData.getColumnName(i)); } while (resultSet.next()) { Object[] row = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { row[i - 1] = resultSet.getObject(i); } tableModel.addRow(row); } // 创建JTable table = new JTable(tableModel); // 添加JTable到JFrame add(new JScrollPane(table)); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { new MySQLJTableExample().setVisible(true); } } ``` 这个示例代码连接到名为"mydatabase"的MySQL数据库,用户名为"root",密码为"mypassword"。它从"mytable"表检索所有记录,并在JTable显示它们。你可以根据自己的需要修改代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值