使用jsp网页端,通过JDBC方式连接数据库,提交输入的内容到数据库。
判断数据库中是否存在已有姓名,如果有就不再重复插入。
输入页
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.util.*"%>
<html>
<head>
<title>hello</title>
</head>
<body>
<form method="post" action="my.jsp">
name:<input type="text" name="username"><br/>
age:<input type="text" name="age">
<input type="submit" value="提 交">
</form>
</body>
</html>
提交页
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.util.*,java.sql.*"%>
<%
String un=request.getParameter("username");
String age=request.getParameter("age");
String driverName = "com.mysql.jdbc.Driver";
String dbURL ="jdbc:mysql://47.93.184.169:3306/xxxx" ;
Driver driver = (Driver)Class.forName(driverName).newInstance();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(dbURL, "xxxxx", "xxxxx");
Statement stat=conn.createStatement();
boolean chongfu=false;
String sq="select * from a1808030220 where username = '"+un+"'";
ResultSet rs = stat.executeQuery(sq);
while (rs.next()) {
int count = rs.getInt(1);
if (count > 0) {
out.print("chongfu");
chongfu=true;
break;
}
}
if(!chongfu)
{
String sql="insert into a1808030220(username,age) values('"+un+"','"+age+"')";
stat.executeUpdate(sql);
out.print("success");
}
stat.close();
conn.close();
%>