java - 返回重复项
问题描述
我尝试使用此代码将我的数据插入到我的数据库中,但我不断重复,我似乎无法弄清楚如何修复它。我是 Java 和 MySQL 的新手,因此非常感谢任何帮助或指导。
以下是我的代码
ApproveButton = new JButton("Approve");
ApproveButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
ApproveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
int rows=table.getRowCount();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo", "root123", "root12345");
PreparedStatement upd = connection.prepareStatement("INSERT INTO approvedsales(productname, quantity, price, total, date) VALUES (?, ?,?,?,? )");
for(int row = 0; row<rows; row++)
{
String productname = (String)table.getValueAt(row, 0);
String quantity = (String)table.getValueAt(row, 1);
String price = (String)table.getValueAt(row, 2);
String total = (String)table.getValueAt(row, 3);
String date = (String)table.getValueAt(row, 4);
upd.setString(1, productname);
upd.setString(2, quantity);
upd.setString(3, price);
upd.setString(4, total);
upd.setString(5, date);
upd.addBatch();
}
upd.executeBatch();
int x = upd.executeUpdate();
if (x == 0) {
JOptionPane.showMessageDialog(ApproveButton, "This is alredy exist");
} else {
JOptionPane.showMessageDialog(ApproveButton,
"Data are successfully stored");
}}
catch(Exception exception){
exception.printStackTrace();
}
}});
ApproveButton.setBounds(129, 204, 89, 23);
contentPane.add(ApproveButton);
我在数据库中的表,所有列都是 varchar(255),没有唯一键和主键
productname quantity price total date
biscuits 1 1 1 7th Sept 2020
解决方案
只使用Statement#executeBatch,而不是 executeUpdate。
int[] xs = upd.executeBatch();
if (IntStream.of(xs).min().orElse(1) == 0) { ...
通过执行executeUpdate,SQL 会被执行两次。
当然,产品表的列定义中的 PRIMARY KEY 会很好。
此外,MySQL 可以将 INSERT 与 UPDATE 选项结合起来,REPLACE 是 - 我相信 - 这个名字。
推荐阅读
- php - 创建一个 for 循环以遍历大量 URL
- react-native - 在 Native Base (React Native) 中的 Accordion 内容中的 JSX
- javascript - 无法读取未定义的属性“地图” - 无法从 axios 请求映射数据
- wso2 - 如何访问和处理发送到 Ballerina 服务资源的 json 数组
- database - Flutter 应用程序是否可以使用 RethinkDB?
- node.js - MongoDB Atlas 连接不断下降
- vim - 为什么启动vim时vim插件'itchyny/lightline.vim'colorscheme没有改变?
- mongoose - Does collection still exists in mongoose?
- java - 指定主题时使用直接交换的 RabbitMQ
- sql-server - 如果我需要按 sql 中的计算列进行分组或过滤,我必须指定两次计算。这是否意味着 SQL Server 工作量翻倍?