请帮我写一个,向MySQL中插入数据的jsp
时间: 2024-02-11 14:08:38 浏览: 34
好的,下面是一个向MySQL数据库中插入数据的JSP示例:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
Connection conn = null;
PreparedStatement pst = null;
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "password");
//创建PreparedStatement对象
pst = conn.prepareStatement("INSERT INTO user(name, age) VALUES(?, ?)");
pst.setString(1, name);
pst.setInt(2, age);
//执行插入操作
pst.executeUpdate();
out.println("数据插入成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭数据库连接和PreparedStatement对象
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
```
在上面的示例中,我们首先获取了从前端传递过来的name和age参数,然后使用JDBC连接MySQL数据库,并创建PreparedStatement对象,最后执行插入操作。
请注意,此示例中的数据库连接信息应该根据你的实际情况进行修改。另外,为了避免SQL注入攻击,请确保对从前端传递过来的参数进行合法性检查和转义。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)