使用Java语言进行编程,数据库连接利用JDBC技术,基于JDBC的小型商品管理系统并在主方法中调用
时间: 2024-03-05 08:48:32 浏览: 18
好的,您的问题是关于使用Java语言编写基于JDBC技术的小型商品管理系统,并在主方法中调用。我可以为您提供一个简单的示例代码,以便您进行参考和学习。以下是代码:
```java
import java.sql.*;
import java.util.Scanner;
public class ProductManagementSystem {
// 定义数据库连接信息
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/productdb";
static final String USER = "root";
static final String PASS = "123456";
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("实例化Statement对象...");
stmt = conn.createStatement();
String sql = "SELECT id, name, price FROM products";
ResultSet rs = stmt.executeQuery(sql);
// 输出查询结果
System.out.println("查询结果:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double price = rs.getDouble("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();
}
}
}
}
```
以上示例代码演示了如何使用Java语言编写一个基于JDBC技术的小型商品管理系统,它连接到一个名为productdb的MySQL数据库,并查询其中的所有商品信息。您可以根据自己的需要进行修改和扩展。