1.项目结构:

2.创建数据库、表、插入记录

create database TestDao;

use TestDao;

create table student(
stuid int,
username varchar(20),
password varchar(20)
); insert student(stuid,username,password)
values ("10001","Eastmount","111111");
insert student(stuid,username,password)
values ("10002","Yangxiuzhang","123456"); desc student; select * from student;

3.创建类:util的Package下创建JDBCConnect.java:

package util;

import java.sql.*;
import com.mysql.jdbc.Driver; public class JDBCConnect { //获取默认数据库连接
public static Connection getConnection() throws SQLException {
return getConnection("TestDAO", "root", "mysql"); //数据库名 默认用户 密码
} //连接数据库 参数:数据库名 root登录名 密码
public static Connection getConnection(String dbName, String userName,
String password) throws SQLException { String url = "jdbc:mysql://localhost:3306/" + dbName
+ "?characterEncoding=utf-8";
//连接MySQL"com.mysql.jdbc.Driver"
DriverManager.registerDriver(new Driver());
return DriverManager.getConnection(url, userName, password);
} //设置 PreparedStatement 参数
public static void setParams(PreparedStatement preStmt, Object... params)
throws SQLException { if (params == null || params.length == 0)
return;
for (int i = 1; i <= params.length; i++) {
Object param = params[i - 1];
if (param == null) {
preStmt.setNull(i, Types.NULL);
} else if (param instanceof Integer) {
preStmt.setInt(i, (Integer) param);
} else if (param instanceof String) {
preStmt.setString(i, (String) param);
} else if (param instanceof Double) {
preStmt.setDouble(i, (Double) param);
} else if (param instanceof Long) {
preStmt.setDouble(i, (Long) param);
} else if (param instanceof Timestamp) {
preStmt.setTimestamp(i, (Timestamp) param);
} else if (param instanceof Boolean) {
preStmt.setBoolean(i, (Boolean) param);
} else if (param instanceof Date) {
preStmt.setDate(i, (Date) param);
}
}
} //执行 SQL,返回影响的行数 异常处理
public static int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql, new Object[] {});
} //带参数执行SQL,返回影响的行数 异常处理
public static int executeUpdate(String sql, Object... params)
throws SQLException { Connection conn = null;
PreparedStatement preStmt = null;
try {
conn = getConnection();
preStmt = conn.prepareStatement(sql);
setParams(preStmt, params);
return preStmt.executeUpdate(); //执行SQL操作
} finally {
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
}
}

4.创建类:bean的Package下创建Student.java:

package bean;

public class Student {

    private Integer id;       //学号
private String name; //姓名
private String password; //密码
public Integer getId() { return id; }
public String getName() { return name; }
public String getPassword() { return password; }
public void setId(Integer id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setPassword(String pwd) { this.password = pwd; }
}

5.创建类:DAO的Package下创建StudentDAO.java:

package DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import bean.Student;
import util.JDBCConnect; public class StudentDAO { //插入学生
public static int insert(Student stu) throws Exception { String sql = "INSERT INTO student (stuid,username,password) VALUES (?,?,?) ";
return JDBCConnect.executeUpdate(sql, stu.getId(),stu.getName(),stu.getPassword());
} //更新学生姓名
public static int update(Student stu) throws Exception { String sql = "UPDATE student SET stuid = ? WHERE username = ? ";
return JDBCConnect.executeUpdate(sql,stu.getId(),stu.getName());
} //删除操作
public static int delete(Integer id) throws Exception { String sql = "DELETE FROM student WHERE stuid = ? ";
return JDBCConnect.executeUpdate(sql, id);
} //查找记录 某学号
public static Student find(Integer id) throws Exception { String sql = "SELECT * FROM student WHERE stuid = ? ";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null; try {
//链接数据库执行SQL语句
conn = JDBCConnect.getConnection(); //连接默认数据库
preStmt = conn.prepareStatement(sql);
preStmt.setInt(1, id);
rs = preStmt.executeQuery();
//获取查询结果
if (rs.next()) {
Student student = new Student();
student.setId(rs.getInt("stuid"));
student.setName(rs.getString("username"));
return student;
} else {
return null;
} } finally { //依次关闭 记录集 声明 连接对象
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
} //查询所有学生信息
public static List<Student> listStudents() throws Exception { List<Student> list = new ArrayList<Student>();
String sql = "SELECT * FROM student";
Connection conn = null;
PreparedStatement preStmt = null;
ResultSet rs = null; try {
conn = JDBCConnect.getConnection();
preStmt = conn.prepareStatement(sql);
rs = preStmt.executeQuery();
while (rs.next()) {
//设置数据库中表参数 否则报错java.sql.SQLException: Column 'id' not found.
Student student = new Student();
student.setId(rs.getInt("stuid"));
student.setName(rs.getString("username"));
student.setPassword(rs.getString("password"));
list.add(student);
} } finally {
if (rs != null)
rs.close();
if (preStmt != null)
preStmt.close();
if (conn != null)
conn.close();
}
return list;
} }

6.index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</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>
This is my JSP page. <br>
<A href="student.jsp">JDBC操作</A>
</body>
</html>

7.student.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:directive.page import="DAO.StudentDAO"/>
<jsp:directive.page import="java.util.List"/>
<%
List studentList = StudentDAO.listStudents();
request.setAttribute("studentList", studentList);
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'student.jsp' starting page</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">
<style type="text/css">
body, td, th, input {font-size:12px; text-align:center; }
</style>
</head> <body>
<form action="operateStudent.jsp" method=get>
<table bgcolor="#CCCCCC" cellspacing=1 cellpadding=5 width=100%>
<tr bgcolor=#DDDDDD>
<th>选择</th>
<th>学号</th>
<th>姓名</th>
<th>密码</th>
<th>操作</th>
</tr> <c:forEach items="${studentList}" var="stu">
<tr bgcolor="#FFFFFF">
<td><input type="checkbox" name="id" value="${stu.id}" /></td>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.password}</td>
<td>
<a href="addEmployee.jsp?action=edit&id=${stu.id}">修改</a>
</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>

8.效果:

本文引用自:http://blog.csdn.net/eastmount/article/details/45833663

JSP_DAO方式实现数据库查询(MyEclipse10,Tomcat7.0,JDK1.7,)——Java Web练习(四)的更多相关文章

  1. Servlet实现数据库查询(MyEclipse10,Tomcat7.0,JDK1.7,)——Java Web练习(三)

    1.MyEclipse | New Web Project :TestServlet01,修改index.jsp的代码: <%@ page language="java" i ...

  2. Servlet实现表单提交(MyEclipse10,Tomcat7.0,JDK1.7,)——Java Web练习(一)

    1.MyEclipse|File|New|Project|Web Project    填写Project Name:exServlet,点选Java EE 6.0(配套Tomcat7.0) 2.代码 ...

  3. 非链接方式访问数据库--查询的数据集用Dataset来存储。

    private void Button_Click_1(object sender, RoutedEventArgs e) { //非链接方式访问数据库, //1创建连接对象(连接字符串) using ...

  4. Java Axis2 1.6.3+JDK1.7.0_13+Tomcat7.0.65+eclipse搭建web service

    安装文件下载: jdk1.7.0_13 安装步骤参考文章:http://jingyan.baidu.com/article/6dad5075d1dc40a123e36ea3.html tomcat7. ...

  5. 动态网站项目(Dynamic Web Project)CRUD(增删改查)功能的实现(mvc(五层架构)+jdbc+servlet+tomcat7.0+jdk1.8),前端使用JSP+JSTL+EL组合

    代码分享链接 https://pan.baidu.com/s/1UM0grvpttHW9idisiqa6rA    提取码:hx7c 图示           项目结构 1.SelectAllUser ...

  6. tomcat7.0建立新的web服务目录

    今天参照网上的配置方法配置了下tomcat的web服务目录,结果总是显示404错误,错误原因是The requested resource is not available.搜索了半天解决方法,终于发 ...

  7. 动态网站项目(Dynamic Web Project)登录功能的实现(mvc(五层架构)+jdbc+servlet+tomcat7.0+jdk1.8)(js验证+cookie)

    1.index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" p ...

  8. Windows Tomcat7.0 安装 Solr

    准备工作 1.下载Tomcat7.0 ,apache-tomcat-7.0.67.exe,安装目录如下:C:\workspace\Tomcat7.0\ 2.下载Solr 5.2,solr-5.2.0. ...

  9. eclipse 使用tomcat7.0建立Dynamic Web Project 时 web.xml的问题

    最近使用Eclipse helios版本结合tomcat7.0建立动态的web项目时,发现在WEB-INF下的web.xml没有了. 解决方案: 建立web项目时,建到第三个下一步时,将 Genera ...

随机推荐

  1. jsonp多次请求报错 not a function的解决方法

    添加时间戳给callbackId $.ajax({ type: "get", url: url, timeout: 6000, data: param, cache: false, ...

  2. IBM总架构师寇文东谈程序员的职业规划

    有些年轻的程序员向我咨询,将来的路该怎么走?俗话说,条条大路通罗马.不同的路都能走向成功,到底选择哪条路,取决于自己的兴趣.可能有程序员会问:如果还没有找到自己的兴趣怎么办?我的建议是多尝试,努力做, ...

  3. 从 IT 中断中学到的最佳监控实践

    每个运维监控工具,一般要追踪数十万个内部性能指标.学会对哪些事件进行告警以及监控确实需要花费想当长的一段时间.因为,并非所有的指标等级都是一致.因此我们需要摸索出一套简单的方法,便于管理所有指标,而且 ...

  4. iOS开发网络篇—多线程断点下载

    iOS开发网络篇—多线程断点下载 说明:本文介绍多线程断点下载.项目中使用了苹果自带的类,实现了同时开启多条线程下载一个较大的文件.因为实现过程较为复杂,所以下面贴出完整的代码. 实现思路:下载开始, ...

  5. ANDROID_MARS学习笔记_S02_014_GSON解析JSON串为对象

    package com.json2; import android.app.Activity; import android.os.Bundle; import android.view.View; ...

  6. 学会使用git

    廖雪峰Git教程 这个教程较为简单,循序渐进 易百Git教程 较为系统 在线代码格式化 可以下载全球最大视频网站的视频支持搜索 点这里

  7. perl use base 继承

    centos6.5:/root/podinns/lib#cat First.pm package First; use base qw(Second); sub new { my $self = {} ...

  8. WCF 托管在IIS中遇到Http的错误

    IIS8中部署WCF服务出错:HTTP 错误 404.3 - Not Found http://www.cnblogs.com/xwgli/archive/2013/03/15/2961022.htm ...

  9. UVA_1025_A_Spy_in_the_Metro_(动态规划)

    描述 https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&a ...

  10. (转载)Linux中cp直接覆盖不提示的方法

    (转载)http://soft.chinabyte.com/os/220/11760720.shtml 新做了服务器,cp覆盖时,无论加什么参数-f之类的还是提示是否覆盖,这在大量cp覆盖操作的时候是 ...