版权声明:如需转载注明出处 https://blog.csdn.net/u011463794/article/details/88626267
传统JDBC开发模式的缺陷
- 控制类的硬编码
- 数据库的频繁开闭
- 连接类的硬编码
一.JDBC的缺陷:
1.连接类:
JDBC进行连接数据库的时候,一般在引入相关jar包后,创建一个数据库连接类,由该类提供数据库驱动的加载、数据库连接参数配置、连接对象的获取及关闭等。而一般该类的实现如下
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database","username","password");
可以看到,数据库驱动名称、数据库连接地址、数据库账号和密码都全部是“硬编码”(硬编码是将数据直接嵌入到程序或其他可执行对象的源代码中的软件开发实践,与从外部获取数据或在运行时生成数据不同。 硬编码数据通常只能通过编辑源代码和重新编译可执行文件来修改)。也就是说当需要修改时,需要修改源码并重新编译,所以拓展性非常差。
因此,如果需要更换其中任何一个数据,都需要重新编译、再上线,会很浪费时间和资源。
最重要一点是:每一个操作数据库的类中,都需要使用上面的连接类,打开连接再关闭,频繁的打开关闭也不好。
2.控制类:
这里放一个我之前做设计时用的DAO类的实现类(DAO(Data Access Object)是一个数据访问接口,数据访问:顾名思义就是与数据库打交道。夹在业务逻辑与数据库资源中间。)也就是对数据库的操作以及查询操作都存在DAOimplement类中
import java.sql.*;
public class GoodDaoImpl implements DAO {
private Connection conn = null;
public GoodDaoImpl(Connection conn) {
this.conn = conn;
}
public int addGood(Good good) {
PreparedStatement stmt = null;
int result = 0;
try {
String sql = "insert into shoppinglist(name,unit,price) values(?,?,?);";
stmt = conn.prepareStatement(sql);
stmt.setString(1, good.getName());
stmt.setInt(2, good.getUnit());
stmt.setFloat(3, good.getPrice());
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public int deleteGood(Good good) {
PreparedStatement stmt = null;
int result = 0;
try {
String sql = "delete from shoppinglist where name =?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, good.getName());
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void showDatabase() {
PreparedStatement stmt = null;
try {
String sql = "select*from shopping";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
这里面可以注意,其中的sql语句以及prepareStatement等也是硬编码,所以也有上面连接类的问题
总而言之,
- 控制类的硬编码
- 数据库的频繁开闭
- 连接类的硬编码