如果用户名username字段为varchar(50),联系方式phone字段为varchar(50),性别sex字段为enum("男","女","保密")在jsp和servlet如何插入数据
时间: 2023-07-19 07:24:23 浏览: 98
在jsp和servlet中插入数据需要先连接数据库,然后使用SQL语句INSERT INTO插入数据。具体步骤如下:
1. 在jsp页面中,通过表单获取用户输入的数据,例如:
```
<form method="post" action="InsertServlet">
<label>用户名:</label>
<input type="text" name="username"><br>
<label>联系方式:</label>
<input type="text" name="phone"><br>
<label>性别:</label>
<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女
<input type="radio" name="sex" value="保密">保密
<br>
<input type="submit" value="提交">
</form>
```
2. 在servlet中获取表单提交的数据,并插入到数据库中,例如:
```
public class InsertServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取表单提交的数据
String username = request.getParameter("username");
String phone = request.getParameter("phone");
String sex = request.getParameter("sex");
// 连接数据库
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 插入数据
String sql = "INSERT INTO user (username, phone, sex) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, phone);
stmt.setString(3, sex);
stmt.executeUpdate();
// 返回插入成功的消息
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Insert Success</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>插入成功!</h1>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
注意,在实际开发中,需要对用户输入的数据进行合法性检查和防止SQL注入攻击。
阅读全文