下面是一个用Java和MySQL编写的停车场管理系统的示例代码:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class ParkingManagementSystem extends JFrame {
private JLabel carNumberLabel;
private JTextField carNumberTextField;
private JButton enterButton;
private JButton exitButton;
private Connection connection;
public ParkingManagementSystem() {
setTitle("停车场管理系统");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
carNumberLabel = new JLabel("车牌号:");
carNumberTextField = new JTextField(10);
enterButton = new JButton("进入");
exitButton = new JButton("离开");
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String carNumber = carNumberTextField.getText();
enter(carNumber);
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String carNumber = carNumberTextField.getText();
exit(carNumber);
}
});
add(carNumberLabel);
add(carNumberTextField);
add(enterButton);
add(exitButton);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/parking", "username", "password");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void enter(String carNumber) {
try {
PreparedStatement statement = connection.prepareStatement("INSERT INTO parking_cars (car_number, enter_time) VALUES (?, NOW())");
statement.setString(1, carNumber);
statement.executeUpdate();
JOptionPane.showMessageDialog(null, "车辆进入停车场");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private void exit(String carNumber) {
try {
PreparedStatement statement = connection.prepareStatement("UPDATE parking_cars SET exit_time = NOW() WHERE car_number = ? AND exit_time IS NULL");
statement.setString(1, carNumber);
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "车辆离开停车场");
} else {
JOptionPane.showMessageDialog(null, "未找到该车辆或该车辆已离开停车场");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ParkingManagementSystem().setVisible(true);
}
});
}
}
上述代码使用了Java的Swing库创建图形用户界面。它包含一个文本框用于输入车牌号码,一个"进入"按钮和一个"离开"按钮。当用户点击"进入"按钮时,程序将将车牌号码和当前时间插入到MySQL数据库的parking_cars
表中。当用户点击"离开"按钮时,程序将更新parking_cars
表中与输入车牌号码匹配且exit_time
为空的记录的exit_time
字段,并给出相应的提示。
请注意,上述代码中的数据库连接URL、用户名和密码需要根据实际情况进行修改。