jsp连接数据库实现登陆注册
时间: 2023-07-13 12:10:09 浏览: 102
首先需要在JSP中导入JDBC驱动,然后建立数据库连接。可以按照以下步骤实现:
1. 导入JDBC驱动
```java
<%@ page import="java.sql.*" %>
```
2. 建立数据库连接
```java
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String username = "root";
String password = "root";
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
```
3. 实现用户注册
```java
String username = request.getParameter("username");
String password = request.getParameter("password");
PreparedStatement pstmt = null;
String sql = "insert into user(username, password) values(?, ?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
4. 实现用户登录
```java
String username = request.getParameter("username");
String password = request.getParameter("password");
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from user where username=? and password=?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
if (rs.next()) {
// 登录成功
} else {
// 登录失败
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
```
以上代码仅供参考,具体实现需要根据具体情况进行调整。
阅读全文