用PreparedStatement方式实现用户注册功能
时间: 2024-05-06 08:17:25 浏览: 16
首先,创建一个名为user的表格,包含id、username和password三个字段。
接下来,使用PreparedStatement方式实现用户注册功能的示例代码如下:
```java
import java.sql.*;
public class UserRegistration {
public static void main(String[] args) throws SQLException {
// 1. 加载JDBC驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 创建数据库连接
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, username, password);
// 3. 使用PreparedStatement执行SQL语句
String sql = "INSERT INTO user(username, password) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "tom");
preparedStatement.setString(2, "123456");
preparedStatement.executeUpdate();
// 4. 关闭资源
preparedStatement.close();
connection.close();
}
}
```
在上述代码中,我们首先加载JDBC驱动程序,然后创建数据库连接。接着,使用PreparedStatement方式执行SQL语句,其中使用占位符?代替实际的参数值,通过调用setString方法设置占位符对应的参数值,最后调用executeUpdate方法执行更新操作。最后,关闭PreparedStatement和Connection对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)