Java JDBC 三层架构实现手机品牌管理 - 代码示例
使用 Java JDBC 和三层架构实现手机品牌管理
本示例使用 Java JDBC 和三层架构,实现一个简单的手机品牌管理系统。用户在控制台输入品牌名称、厂商名称和产地,系统会判断该品牌是否存在,如果不存在则将其插入数据库。
功能需求:
- 品牌名称、厂商名称和产地都必须输入。
- 输入完整的信息后,应先判断数据库中是否已经存在该品牌。
- 输入完整信息后,如果该品牌在数据库中不存在,则进行添加内容。
代码实现:
1. 数据库操作层 (DBUtil.java)
import java.sql.*;
public class DBUtil {
private static final String DRIVER = 'com.mysql.jdbc.Driver';
private static final String URL = 'jdbc:mysql://localhost:3306/mobile';
private static final String USERNAME = 'root';
private static final String PASSWORD = '123456';
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs, Statement stmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. 业务逻辑层 (MobileService.java)
import java.sql.*;
import java.util.Scanner;
public class MobileService {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print('请输入品牌名称:');
String brand = scanner.nextLine();
System.out.print('请输入厂商名称:');
String manufacturer = scanner.nextLine();
System.out.print('请输入产地:');
String origin = scanner.nextLine();
if (isBrandExist(brand)) {
System.out.println('该品牌已存在!');
} else {
insertMobile(brand, manufacturer, origin);
System.out.println('添加成功!');
}
}
public static boolean isBrandExist(String brand) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = 'SELECT * FROM mobile WHERE brand=?';
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, brand);
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, pstmt, conn);
}
return false;
}
public static void insertMobile(String brand, String manufacturer, String origin) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtil.getConnection();
String sql = 'INSERT INTO mobile (brand, manufacturer, origin) VALUES (?, ?, ?)';
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, brand);
pstmt.setString(2, manufacturer);
pstmt.setString(3, origin);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(null, pstmt, conn);
}
}
}
3. 用户界面层 (MobileUI.java)
public class MobileUI {
public static void main(String[] args) {
MobileService.main(null);
}
}
使用方法:
- 确保数据库已创建并存在名为 'mobile' 的表,该表包含字段 'brand'、'manufacturer' 和 'origin'。
- 将 DBUtil.java 中的数据库连接信息修改为您的实际配置。
- 编译并运行 MobileUI.java。
- 在控制台输入品牌名称、厂商名称和产地,系统将判断该品牌是否存在并进行相应的操作。
注意:
- 本示例仅供学习参考,实际应用中需要根据具体需求进行调整和完善。
- 数据库操作部分应该使用预编译语句,防止 SQL 注入攻击。
- 代码中使用了 'try-with-resources' 语句,确保资源能够正常关闭。
- 可以使用日志记录功能,方便调试和排查问题。
原文地址: https://www.cveoy.top/t/topic/kyGm 著作权归作者所有。请勿转载和采集!