一.BaseDao是什么
BaseDao是为了解决数据库中增删改查而的提供的一个定义类!
二.BaseDao的操作
1、连接数据库
private String driver = "com.mysql.cj.jdbc.Driver";// 数据库驱动字符串
private String url = "jdbc:mysql://localhost:3306/20240322db?serverTimezone=GMT%2B8";// 连接URL字符串
private String user = "root"; // 数据库用户名
private String password = "root"; // 用户密码
Connection conn = null; // 数据连接对象
2、数据库连接异常和关闭连接
//数据库连接
public Connection getconnection(){
Connection con=null;
try {
if(conn==null){
Class.forName(driver);
con= DriverManager.getConnection(url,user,password);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace(); //处理连接异常
}
return con;
}
public void closeAll(Connection conn, PreparedStatement pst,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
if(pst!=null){
pst.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
3、增删改可共用同一个方法
参数解释:
sql:SQL表达式
objs:一个获取值的数组(例:可能改一个值,也有可能改多个值)
public int Update(String sql,Object []objs){
int row=0;
Connection conn=getconnection();
try {
//预处理对象
PreparedStatement pst=conn.prepareStatement(sql);
//数据注入
for (int i = 0; i < objs.length; i++) {
pst.setObject(i+1,objs[i]);
}
//处理数据
row=pst.executeUpdate();
//释放资源
closeAll(conn,pst,null);
} catch (SQLException e) {
e.printStackTrace();
}
return row;
}
4、查询方法
按需求写查询方法!
public List<Bao> select(){ //针对查询方法
List<Bao> lis=null;
Connection conn=getconnection();
String sql="select * from t_user";
ResultSet rs=null;
PreparedStatement pst=null;
try {
//预处理对象
pst=conn.prepareStatement(sql);
rs=(ResultSet) pst.executeQuery();
while (rs.next()){
Bao b=new Bao();
b.setId(rs.getInt("id"));
b.setName(rs.getString("name"));
b.setPassword(rs.getString("password"));
b.setAge(rs.getInt("age"));
lis.add(b);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
this.closeAll(conn,pst,rs);
}
return lis;
}
总结:这是比较简单的java连接数据库,可用于jsp等等