今天下雪了
学习了Javaweb基础,增加操作,今天代码如下
package dao;标签:java,rs,11.10,st,sql,import,conn From: https://www.cnblogs.com/wangzelin/p/17824916.html
import bean.Bean;
import utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Dao {
private Connection conn = null;
private PreparedStatement st=null;
private ResultSet rs=null;
public List<Bean> Query(String name) {
// 创建一个arraylist集合 填充数据库表数据
ArrayList<Bean> list = new ArrayList<>();
try {
// 获取数据库连接对象
conn = DBUtils.getConnection();
String sql = "SELECT * FROM test01 WHERE name LIKE ?";
st = conn.prepareStatement(sql);// 将sql存放入小汽车中搬运
st.setString(1, "%" + name + "%");
rs = st.executeQuery();// 获取结果
// 使用while循环读取resultset数据
while (rs.next()) {
Bean sr = new Bean();
sr.setId(rs.getInt("id"));
sr.setName(rs.getString("name"));
sr.setType(rs.getString("type"));
sr.setUploadDate(rs.getString("uploadDate"));
// 将对象保存到对应arraylist
list.add(sr);
}
} catch (SQLException e) {
// 异常抛出
e.printStackTrace();
} finally {
// 使用之后关闭连接
DBUtils.close(rs, st, conn);
}
// 返回最终结果
return list;
}
public boolean add(Bean bean) {
try{
conn = DBUtils.getConnection();
String sql="insert into test01(name,type,uploadDate) VALUES (?,?,?)";
st =conn.prepareStatement(sql);
st.setString(1,bean.getName());
st.setString(2,bean.getType());
st.setString(3,bean.getUploadDate());
return st.executeUpdate() > 0;
}catch (SQLException e){
e.printStackTrace();
}finally {
DBUtils.close(rs, st, conn);
}
return false;
}
}