1. 创建数据库
mysql> create database myWeb;
Query OK, 1 row affected (0.00 sec)
mysql> use myWeb;
Database changed
mysql> create table customers(
-> customerId varchar(20) primary key,
-> name varchar(20),
-> phone varchar(20)
-> );
Query OK, 0 rows affected (0.06 sec)
mysql> insert into customers(customerId,name,phone) value('001','gao','12345');
Query OK, 1 row affected (0.03 sec)
mysql> insert into customers(customerId,name,phone) value('002','li','1257');
Query OK, 1 row affected (0.03 sec)
2. 编写一个映射数据库中的表的类
package beans;
public class Customer {
private String cusid,cusname,cusphone;
public Customer()
{
}
public String getCusid() {
return cusid;
}
public void setCusid(String cusid) {
this.cusid = cusid;
}
public String getCusname() {
return cusname;
}
public void setCusname(String cusname) {
this.cusname = cusname;
}
public String getCusphone() {
return cusphone;
}
public void setCusphone(String cusphone) {
this.cusphone = cusphone;
}
}
3. 编写一个操作类,实现数据库的查询
package dao;
import java.sql.*;
import java.util.*;
import beans.Customer;
public class CustomerDao {
public List
{
List
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/myWeb", "root", "sql");
Statement cmd=con.createStatement();
ResultSet rs=cmd.executeQuery("select * from customers");
while(rs.next())
{
Customer c=new Customer();
c.setCusid(rs.getString(1));
c.setCusname(rs.getString(2));
c.setCusphone(rs.getString(3));
list.add(c);
}
}
catch(Exception ex)
{}
return list;
}
}
4. 编写jsp客户端,调用操作类。并使用JSTL标签显示顾客信息
<%@ page contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="dao.CustomerDao,java.util.*,beans.Customer" %>
<html>
<body>
<%
CustomerDao dao=new CustomerDao();
List
pageContext.setAttribute("cuslist",clist);
%>
<table>
<tr>
<td>顾客IDtd>
<td>姓名td>
<td>联系电话td>
tr>
<c:forEach var="cus" items="${cuslist}">
<tr>
<td>${cus.cusid }td>
<td>${cus.cusname }td>
<td>${cus.cusphone }td>
tr>
c:forEach>
table>
body>
html>
运行结果: