jsp连接数据库实现
时间: 2024-01-27 22:13:12 浏览: 91
以下是使用JSP连接数据库的步骤和示例代码:
1. 导入JDBC驱动程序
```jsp
<%@ page import="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
%>
```
2. 建立数据库连接
```jsp
<%
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
%>
```
3. 执行SQL语句
```jsp
<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next()){
out.println(rs.getString("name")); }
%>
```
完整的JSP连接数据库的示例代码如下:
```jsp
<%@ page import="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next()){
out.println(rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
%>
```
阅读全文