jsp与数据库连接

来源:互联网 发布:linux学了有什么用 编辑:程序博客网 时间:2024/05/17 06:56

(1)把mysql的驱动放到tomcat的lib中 驱动是这个
http://ftp.up.ac.za/pub/windows/MySQL/Downloads/Connector-J/mysql-connector-java-5.1.6.zip
解压后在lib中有mysql-connector-java-5.1.6.jar.把这个文件放到tomcat的lib中5.X的在tomcat/common/lib 6.0在tomcat/lib
(2)建一个很简单的表person就两个字段username和password,数据库名和数据库密码换成你的就是了
create database ibatis;--创建数据库
use ibatis;--使用数据库,以下表在该数据库中
create table person(username varchar(20),password varchar(20));--创建person表

(3)创建index.jsp和regist.jsp
1:
index.jsp 提交表单页面
<%@ page pageEncoding="GBK"%>

<html>
<head>
</head>

<body>
<form action="regist.jsp" method="post">
username :<input type = "text" name="name"/>
password :<input type = "password" name="password"/>
<input type = "submit" value="提交"/>
</form>
</body>
</html>
2:regist.jsp //用户注册同时显示所有用户

<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.sql.*"%>
<body>
<center>
<%
request.setCharacterEncoding("GBK");
String uname=request.getParameter("name"); //从表单获得
String pwd=request.getParameter("password"); //从表单获得
String driver="com.mysql.jdbc.Driver"; //我用的是mysql官方驱动你自己换一下就是了 在这里有
String url="jdbc:mysql://localhost:3306/ibatis?user=root&password=yanghao"; //这是数据库连接地址Ibatis是数据库名称,user是用户.password就是你的用户名,根据实际情况你修改
String sql="INSERT INTO person (username,password) VALUES('"+uname+"','"+pwd+"')"; //把index.jsp提交的两个数据插进数据库的数据库语句
Connection conn=null; //数据库连接
Statement stmt=null;
ResultSet rs = null; //查询结果
%>
<%
Class.forName(driver); //加载驱动
conn=DriverManager.getConnection(url); //获得连接
stmt=conn.createStatement();
stmt.execute(sql);//存入数据库
rs=stmt.executeQuery("select * from person"); //查询所有person语句
%>
<%
if(rs!=null){ //判断以下

while(rs.next()){
String username=rs.getString(1);
String password=rs.getString(2);
%>
<table>
<tr>
<td><%=username %></td>
<td><%=password %></td>
</tr>
</table>
<%
//关闭数据库连接,和开始的顺序是反的
rs.close();//关闭结果集
stmt.close();//关闭Statement
conn.close();//关闭数据库连接
//ok完成了插入和查询操作

}
}
%>
</center>
</body>