数据库操作 内容和要求: (1)(考察知识点DBCP数据源) 应用DBCP数据源,实现获取数据库连接对象的功能,并实现增删改查任务代码的编写。 (2)(考察知识点Druid数据源) 使用Druid数据源,实现获取数据库连接对象的功能,并实现增删改查任务代码的编写。
时间: 2024-04-28 07:21:17 浏览: 65
以下是使用 DBCP 数据源和 Druid 数据源实现增删改查的示例代码:
使用 DBCP 数据源:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class DBCPServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获取数据库连接
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/mydb");
conn = ds.getConnection();
// 执行增删改查操作
pstmt = conn.prepareStatement("SELECT * FROM users WHERE name = ?");
pstmt.setString(1, "张三");
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("姓名:" + rs.getString("name"));
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
使用 Druid 数据源:
```java
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DruidServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DruidDataSource ds = new DruidDataSource();
ds.setUrl("jdbc:mysql://localhost:3306/mydb");
ds.setUsername("root");
ds.setPassword("password");
DruidPooledConnection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获取数据库连接
conn = ds.getConnection();
// 执行增删改查操作
pstmt = conn.prepareStatement("SELECT * FROM users WHERE name = ?");
pstmt.setString(1, "张三");
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("姓名:" + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ds.close();
}
}
```
需要注意的是,使用 DBCP 数据源需要在 Tomcat 的 context.xml 文件中配置数据源,而使用 Druid 数据源则需要添加 Druid 的依赖,具体操作可以参考各自的官方文档。
阅读全文