gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:07:05 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com