idea 用JFrame创建页面,写出能够链接数据库的商品购物功能的代码
时间: 2024-02-29 21:51:13 浏览: 24
好的,以下是使用 Java Swing 编写能够链接数据库的商品购物功能的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class MainFrame extends JFrame implements ActionListener {
private JPanel panel;
private JLabel label1, label2, label3;
private JTextField textField1, textField2, textField3;
private JButton button1, button2;
private Connection connection;
private Statement statement;
public MainFrame() {
super("商品购物");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 300);
panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
label1 = new JLabel("商品编号:");
textField1 = new JTextField();
label2 = new JLabel("商品名称:");
textField2 = new JTextField();
label3 = new JLabel("商品单价:");
textField3 = new JTextField();
button1 = new JButton("购买");
button1.addActionListener(this);
button2 = new JButton("清空");
button2.addActionListener(this);
panel.add(label1);
panel.add(textField1);
panel.add(label2);
panel.add(textField2);
panel.add(label3);
panel.add(textField3);
panel.add(button1);
panel.add(button2);
add(panel);
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "123456");
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
// 购买商品
String id = textField1.getText();
String name = textField2.getText();
String price = textField3.getText();
try {
// 查询是否存在该商品
ResultSet resultSet = statement.executeQuery("SELECT * FROM goods WHERE id=" + id);
if (resultSet.next()) {
// 更新商品库存和销量
int stock = resultSet.getInt("stock");
int sales = resultSet.getInt("sales");
if (stock > 0) {
statement.executeUpdate("UPDATE goods SET stock=" + (stock - 1) + ", sales=" + (sales + 1) + " WHERE id=" + id);
JOptionPane.showMessageDialog(panel, "购买成功!");
} else {
JOptionPane.showMessageDialog(panel, "库存不足!");
}
} else {
JOptionPane.showMessageDialog(panel, "该商品不存在!");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (e.getSource() == button2) {
// 清空输入框内容
textField1.setText("");
textField2.setText("");
textField3.setText("");
}
}
public static void main(String[] args) {
new MainFrame();
}
}
```
这个示例代码使用了 MySQL 数据库,数据库名为 `shop`,用户名为 `root`,密码为 `123456`。购买商品时,会查询数据库中是否存在该商品,如果存在则更新商品库存和销量。购买成功后会弹出提示框,如果库存不足或商品不存在也会弹出相应的提示框。