java - 无法从 JTable 数据库获取数据到 JTextField

标签 java mysql jdbc

我的 Jtable 连接到我创建的数据库,以便它可以在我的 GUI 中显示所有数据。但是我试图将数据从我的 JTable 获取到 JTextField。就像当您单击表格的行时,表格内数据库中的数据将转到 TextField。但是当我点击表格时,它显示了这样的错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'NO.='1 RASCHEL" at line 1

我一直在寻找答案,但找不到。请帮助我,自周五以来我一直坚持这个错误。

table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) {
        int row = table.getSelectedRow();
        String table_click = (table.getModel().getValueAt(row, 0).toString());
        try {
            String query = "SELECT * FROM `raschel` where MACHINE NO.='" + table_click + "'";
            Connection con;
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                String machine = rs.getString("MACHINE NO.");
                String type = rs.getString("TYPE");
                String product = rs.getString("PRODUCT");
                txtMachine.setText(machine);
                txtType.setText(type);
                txtProd.setText(product);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
});

最佳答案

您正在使用的列 MACHINE NO. 包含一个空格和一个点,以便与您必须将名称放在两者之间的类似名称一起使用:

`MACHINE NO.`

所以你的查询应该是这样的:

String query = "SELECT * FROM `raschel` where `MACHINE NO.`='" + table_click + "'";

但这仍然不能防止语法错误或 SQL 注入(inject),因此您可以使用:

String query = "SELECT * FROM `raschel` where `MACHINE NO.` = ?";
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","");
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, table_click);//<<-----------set the parameter like this
ResultSet rs = ps.executeQuery();

关于java - 无法从 JTable 数据库获取数据到 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913358/

相关文章:

Java 1.8 Diffie Hellman Group 14 返回 InvalidAlgorithmException

mysql - MySQL中嵌套IF的评估

php - 为什么 mysql_connect 会破坏我的 .php?

postgresql - 无法使用 apache drill 1.2 配置 postgreSQL JDBC 驱动程序

未捕获 Java 异常

java - StringBuffer 在线程安全程序的设计中到底是如何工作的?

java - 使用 JUnit 进行单元测试

php - 无法使用 PHP 使 SQL 更新工作

java - 无法连接到远程MySQL服务器

java - 将数据从应用程序(Java)导入临时表的最快方法是什么?