jsp与数据库连接

(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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值