插入数据库

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.logging.*" %>
<%@page import="com.mysql.jdbc.Driver" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>注 册</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPasswd="root";
String dbName="mysql";
String url="jdbc:mysql://localhost:3306/hw?user=root&password=root";
Class.forName(driverName);
Connection conn =DriverManager.getConnection(url);
//以上是注册驱动并连接数据库的公共代码
String sql="Insert into info(username,password)values(?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
request.setCharacterEncoding("UTF-8");
//设置字符编码,避免出现乱码
String username=request.getParameter("username");
String password=request.getParameter("password");
pstmt.setString(1, username);
pstmt.setString(2, password);
int n=pstmt.executeUpdate();
if(n==1){%> 注册成功!<br><% }
else {%>注册失败!<br> <%}
if(pstmt!=null){pstmt.close();}
if(conn!=null){conn.close();}
%>
<a href="1.jsp">点击此处返回登录</a>
</body>
</html>

原文地址:https://www.cnblogs.com/frankzone/p/7725868.html