且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我必须使用按钮将特定行从mysql添加到JTable

更新时间:2023-12-03 11:22:46

这不是您问题的具体答案,但有一些提示希望可以帮助您自己解决问题.

This is not a concrete answer to your problem but some hints that hopefully will help you to solve it by yourself.

当心数据库调用是耗时的任务,可能会阻止事件分派导致GUI响应的线程(EDT). EDT是一个单独的特殊线程,在该线程中可以创建和更新Swing组件.为避免阻塞该线程,请考虑使用 SwingWorker 在后台线程中执行数据库调用并更新EDT中的Swing组件.在 Swing并发跟踪中了解更多.

Beware database calls are time consuming tasks and may block the Event Dispatch Thread (EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.

根据文档,使用 DiverManager.getConnection( )不建议使用,应替换为 MySQL JDBC连接器,实现应如下所示:

According to the documentations, the use of DiverManager.getConnection() is discouraged and should be replaced by DataSource.getConnection() instead. Using MySQL JDBC Connector the implementation should look like this:

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("inventry");
dataSource.setPortNumber(3306);
dataSource.setUser("root");
dataSource.setPassword(""); // blank password is a terrible idea

Connection connection = dataSource.getConnection();

在本文中查看更多信息:与数据源对象连接

See more in this article: Connecting with DataSource Objects

如果要使用JDBC,请使用 PreparedStatement :

If you are going to use JDBC then use PreparedStatement:

String pid = prid.getText().trim();
...
String sql = "SELECT * FROM addproducts WHERE pid = ?";
PreparedStatemnt ps = connection.prepareStatement(sql);
ps.getString(1, pid);
ResultSet rs = ps.executeQuery();

注1: 您确定pidString是个好主意吗?
注释2: 要基于文本字段值填充表格,请参见

Note 1: Are you sure is a good idea pid be a String?
Note 2: To populate your table based on text fields values see this related question and answer.

自Java 7起,有一种更优雅的方式来处理try-catch块和可关闭资源:尝试使用资源:

Since Java 7 there's a more elegant way to deal with try-catch blocks and closeable resources: try-with-resources:

try (Connection connection = dataSource.getConnection();
     PreparedStatement statement = connection.prepareStatement("sql")) {

    statement.setString(1, "pid");

    try (ResultSet resultSet = statement.executeQuery()) {

        // process ResultSet here

    } catch (SQLException ex) {
        // Log the exception here
    }

} catch (SQLException ex) {
    // Log the exception here
}