一、创建数据库
1.进入mysql
2.创建表格
3.查看表格
4.插入数据
5.查看插入后的表
二、myeclipse建立连接数据库
在tomcat中的lib中放入mysql-connector-java-5.1.34.jar这个包
三、JSP读取数据库
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'testconnection.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>
<%
String url="jdbc:mysql://localhost/ch08";
String userName="root";
String password="123456";
String sql=null;
Connection conn=null;
Statement stmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
out.println("加载驱动器类时出现异常");
}
try{
conn=DriverManager.getConnection(url,userName,password);
stmt=conn.createStatement();
sql="select * from user";
ResultSet rs=stmt.executeQuery(sql);
%>
<table width="740" border="1" cellspacing="0" cellpadding="6">
<tr>
<td width="100" align="center" valign="middle">姓名</td>
<td width="145" align="center" valign="middle">性别</td>
<td width="145" align="center" valign="middle">年龄</td>
</tr>
<%
while(rs.next())
{
String name=rs.getString(1);
String sex=rs.getString(2);
int age=rs.getInt(3);
%>
<tr>
<td height="40" align="center" valign="middle"><%=name%></td>
<td height="40" align="center" valign="middle"><%=sex%></td>
<td height="40" align="center" valign="middle"><%=age%></td>
</tr>
<%
}
rs.close();
stmt.close();
}
catch(SQLException e){
out.println("连接数据库的过程中出现异常");
}
if(conn==null)
out.println("\n数据库连接失败");
else
out.println("数据库连接成功");
try{
if(conn!=null)
conn.close();
}
catch(SQLException e)
{
out.println("关闭数据库连接时出现SQl异常");
}
%>
</table>
</body>
</html>