写一个商品管理系统的代码,要用到mysql和JDBC
时间: 2024-03-24 11:37:33 浏览: 21
好的,下面是一个简单的商品管理系统的代码,使用了MySQL数据库和JDBC连接:
```java
import java.sql.*;
public class ProductManagementSystem {
// JDBC连接驱动和数据库连接信息
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/productdb";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册JDBC驱动
Class.forName(JDBC_DRIVER);
// 打开连接
System.out.println("连接到数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("创建商品表...");
stmt = conn.createStatement();
String sql = "CREATE TABLE products " +
"(id INTEGER not NULL, " +
" name VARCHAR(255), " +
" price FLOAT, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("商品表创建成功!");
// 插入数据
System.out.println("插入商品数据...");
sql = "INSERT INTO products " +
"VALUES (1, '商品1', 10.99)";
stmt.executeUpdate(sql);
sql = "INSERT INTO products " +
"VALUES (2, '商品2', 19.99)";
stmt.executeUpdate(sql);
sql = "INSERT INTO products " +
"VALUES (3, '商品3', 30.50)";
stmt.executeUpdate(sql);
System.out.println("商品数据插入成功!");
// 查询数据
System.out.println("查询商品数据...");
sql = "SELECT id, name, price FROM products";
ResultSet rs = stmt.executeQuery(sql);
// 输出查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
float price = rs.getFloat("price");
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);
}
rs.close();
// 关闭连接
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理JDBC错误
se.printStackTrace();
} catch (Exception e) {
// 处理Class.forName错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("程序执行完毕!");
}
}
```
这个程序会创建一个名为`productdb`的数据库,并在其中创建一个名为`products`的表,然后插入一些数据,并查询出这些数据。注意替换代码中的数据库URL、用户名和密码,以及修改插入数据和查询数据的语句,以符合你的实际需求。