servlet连接mysql数据库
时间: 2023-11-14 08:07:54 浏览: 115
在servlet中连接MySQL数据库,需要先下载对应的MySQL数据库连接驱动包,然后在代码中加载驱动程序,建立连接对象,创建语句对象,最后执行SQL语句。以下是一个简单的示例代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接对象
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 创建语句对象
String sql = "select * from user";
pstmt = conn.prepareStatement(sql);
// 执行SQL语句
rs = pstmt.executeQuery();
// 处理结果集
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("name: " + name + ", age: " + age);
}
} catch (Exception 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();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
阅读全文