1.将数据库中的数据传入eclipse
使用mysql数据库,使用NavicatPremium进行数据库连接与创建(NavicatPremium资源https://download.csdn.net/download/a11548796/85318752)
创建一个名为test的数据库,在test数据库中建立名为users的数据表
在users中创建相应字段
插入数据
下载地址:MySQL :: MySQL Community Downloads,找到与MySQL对应的驱动程序进行下载。
将下载好的数据库驱动程序jar包复制到WebContent\WEB-INF\lib
创建jsp文件,在.jsp的<body>与</body>中间加入代码
<%
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");(数据库名称与密码)
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from users");
while (rs.next()){
out.print(rs.getString("username"));
}
rs.close();
st.close();
conn.close();
%>
运行后的结果:
2.在JSP页面中使用JDBC技术操作数据库
设计一个查询页面
实现输入一个姓名查询出结果的功能
整体代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询参数</title>
</head>
<body>
<center>
<form action="" method="post">
请输入查询的姓名:<input type="text" name="name">
<input type="submit" name="submit" value="查询">
</form>
</center>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
if(name!=null){
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?charaterEncoding=utf-8","root","root");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from users where username='" + name + "'");
out.print("<table border='1' align='center'>");
while (rs.next()) {
out.print("<tr>");
out.print("<td>" + rs.getInt("id") + "</td>");
out.print("<td>" + rs.getString("username") + "</td>");
out.print("<td>" + rs.getString("password") + "</td>");
out.print("<td>" + rs.getString("gender") + "</td>");
out.print("<td>" + rs.getString("email") + "</td>");
out.print("<td>" + rs.getString("province") + "</td>");
out.print("<td>" + rs.getString("city") + "</td>");
out.print("<td>" + rs.getDate("birthday") + "</td>");
out.print("</tr>");
}
out.print("</table>");
rs.close();
st.close();
conn.close();
}
else{
out.print("<center><h4>请输入查询的姓名!</h4></center>");
}
%>
</body>
</html>
结果展示: