jsp mysql连接实例

要解释一下... 要解释一下 展开
 我来答
yanghaoynu
推荐于2016-01-28 · TA获得超过625个赞
知道小有建树答主
回答量:311
采纳率:0%
帮助的人:349万
展开全部
面是一个纯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>
百度网友a57efd2
2009-06-26 · TA获得超过3010个赞
知道小有建树答主
回答量:606
采纳率:100%
帮助的人:274万
展开全部
//myDB为数据库名
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
Connection conn= DriverManager.getConnection(url);
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式