jsp访问数据库
1.使用jsp小脚本:<%java代码%>,就是在其中写入jdbc代码。
2.导包操作
a.java项目:
首先,将jar包复制到工程;
然后,右键该jar包—>build path—>add to build path
b.web项目:
将jar包复制到WEB-INF/lib目录下即可
3.核心就是将java中的jdbc代码复制到jsp中
应用实例:写一个index.jsp页面与check.jsp页面,将index.jsp页面的表单元素提交到check.jsp页面,check.jsp页面要实现数据库的访问,由此判断登录是否成功
要使用到的数据库与数据表
create database test;
use test;
create table login(
l_id int not null primary key,
l_name varchar(20) not null,
l_pwd varchar(20) not null
)
insert into login values(1,'zs','abc');
select * from login;
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check.jsp" method="post">
用户名:<input type="text" name="uname"><br>
密码:<input type="password" name="upwd"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String URL = "jdbc:mysql://127.0.0.1:3306/test";
String USERNAME = "root";
String PWD = "123abc";
String DRIVER="com.mysql.jdbc.Driver";
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try {
//1.加载具体的驱动类:Class.forName()
Class.forName(DRIVER);
//2.连接数据库:DriverManager.getConnection()
con=DriverManager.getConnection(URL,USERNAME,PWD);
//3.获取操作数据库对象:con.createStatement()
stmt=con.createStatement();
String name=request.getParameter("uname");
String pwd=request.getParameter("upwd");
String sql="select count(*) from login where l_name='"+name+"' and l_pwd='"+pwd+"'";
//4.返回到结果集rs
rs=stmt.executeQuery(sql);
//5.获取数据:rs.next(),rs.getXXX()
int count=-1;
while(rs.next()!=false) {
count=rs.getInt(1);
}
if(count>0)
out.println("登录成功!");
else
out.println("登录失败!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
//关闭jdbc三幻神(类似与栈的顺序:先开先关)
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
%>
</body>
</html>
运行结果图:
输入正确的用户名与密码
输入错误的用户名或密码