DBCP封裝與使用——資料庫增刪改查
阿新 • • 發佈:2019-02-01
1、準備
2、資料庫配置檔案
#基本查詢的設定
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://連線名:3306/資料庫名?characterEncoding=utf8
username=u_show
password=17100886
3、DBCPUtils.java工具類
public class DBCPUtils {
private static DataSource dataSource;
//載入配置檔案,建立資料庫連線池
static {
try {
InputStream is = DBCPUtils.class.getResourceAsStream("/dbcp.properties");
Properties p = new Properties();
p.load(is);
dataSource = BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
e.printStackTrace();
}
}
//返回連線物件
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("資料連接獲取失敗!");
}
}
//返回連線池物件
public static DataSource getDataSource() {
return dataSource;
}
//釋放連線,被連線池收回
public static void releaseConnection(Connection connection, PreparedStatement pstmt, ResultSet rs){
try {
if(rs != null ) {
rs.close();
}
if(pstmt != null ) {
pstmt.close();
}
if(connection != null ) {
connection.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
//利用main函式測一下是否連線成功
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBCPUtils.getConnection();
stmt = conn.prepareStatement("select * from User");
rs = stmt.executeQuery();
while (rs.next()) {
User user = new Lqsjrkqk(rs.getString(1), rs.getString(2));
System.out.println(
rs.getString(1) + " " +
rs.getString(2) + " "
);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCPUtils.releaseConnection(conn, stmt, rs);
}
}
}
4、資料庫增刪改查(PreparedStatement )
1、查詢
public ArrayList<Gljhlqrs> selectAll() {
ArrayList<Gljhlqrs> lists = new ArrayList<>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBCPUtils.getConnection();
stmt = conn.prepareStatement("select * from t_tj_gljhlqrs order by XH");
rs = stmt.executeQuery();
while (rs.next()) {
Gljhlqrs lqrs = new Gljhlqrs(rs.getInt(1), rs.getString(2),
rs.getString(3), rs.getInt(4));
lists.add(lqrs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCPUtils.releaseConnection(conn, stmt, rs);
}
return lists;
}
2、插入、刪除、更新
public boolean ChaRu1(User user){
boolean flag=true;
Connection conn = null;
PreparedStatement stmt = null;
String insertSql="insert into user (name,pwd) values(?,?)";
String deleteSql ="delete from user where name=?";
String updateSql = "";
// getConn()方法是靜態的,直接用類呼叫建立連線。
try {
conn = DBCPUtils.getConnection();
stmt = conn.prepareStatement(insertSql);
stmt .setString(1, user.getName());
stmt .setString(2, user.getPwd());
//這裡以插入為例,其他的改一下sql即可,程式碼一樣。
int i=stmt .executeUpdate();
if(i==0){
flag=false; //更新失敗
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBCPUtils.releaseConnection(conn, stmt, null);
//關閉連線,由於插入操作不涉及ResultSet類,故其物件rs無需關閉,用null代替。
}
return flag;
}