首页 课程 师资 教程 报名

JavaWeb数据库连接的简单操作

  • 2022-03-17 10:45:15
  • 688次 星辉

在mysql建表如下:

创建登录界面jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<body>
<form action="log.jsp" method="post">
姓名:<input type="text" name="name"><br>
密码:<input type="text" name="pwd"><br><br>
<input type="submit" value="登录">&nbsp;&nbsp;&nbsp;
<input type="reset" value="取消">
</form>
</body>
</html>

创建后台连接数据库log.jsp

<%@ page language="java" import="java.util.*" import="java.sql.*" pageEncoding="utf-8"%>
<html>
<body>
<%String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="123456";
String dbName="userlog";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user="+userName+"&password="+userPwd;
String url3="&useUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driverName);
Connection conn=DriverManager.getConnection(url);
String user=request.getParameter("name");
String password=request.getParameter("pwd");
String sql="select * from user where name=? and password=?";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1,user);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
%><center><h1>登陆成功!</h1></center>
<%}
else {
%><center><h1>用户名或密码错误!</h1></center>
<%}
if(rs != null) {rs.close();}
if(pstmt!=null){pstmt.close();}
if(conn!=null){conn.close();}
%>
</body>
</html>

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交