怎么用Servlet连接mysql数据库 给个例题

 我来答
lixingwu_1
2011-12-20 · TA获得超过160个赞
知道小有建树答主
回答量:135
采纳率:0%
帮助的人:73.7万
展开全部
package com.jsp.Database;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.microsoft.jdbc.sqlserver.SQLServerDriver;
public class JDBCServlet extends HttpServlet
{
/* 连接数据库属性*/
String driver;
String password,url,user;
/*处理doGet */

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException
{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
try
{
Connection con=getConnection();
Statement stmt=con.createStatement();
ResultSet rst=stmt.executeQuery("select * from user_info");
while(rst.next())
{
out.println(rst.getString("userid"));
out.println("<br>");

}
rst.close();
stmt.close();
con.close();

}
catch(SQLException e)
{
e.printStackTrace();
}
}
/*处理doPost请求*/
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException
{
doGet(request,response);
}

public void init()throws ServletException
{
driver=getInitParameter("DRIVER");
password=getInitParameter("PASSWORD");
url=getInitParameter("URL");
user=getInitParameter("USER");
}
private Connection getConnection()
{
Connection con=null;
try
{
Class.forName(driver);
con=DriverManager.getConnection(url,user,password);

}
catch(Exception e )
{
e.printStackTrace();
}

return con;

}

}

======== web.xml文件配置========

<servlet>
<servlet-name>JDBCServlet</servlet-name>
<servlet-class>com.jsp.Database.JDBCServlet</servlet-class>
<init-param>
<param-name>DRIVER</param-name>
<param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
</init-param>

<init-param>
<param-name>URL</param-name>
<param-value>jdbc:jdbc:mysql://127.0.0.1:3306/数据库名</param-value>
</init-param>

<init-param>
<param-name>USER</param-name>
<param-value>用户名</param-value>
</init-param>
<init-param>

<param-name>PASSWORD</param-name>
<param-value>密码</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>JDBCServlet</servlet-name>
<url-pattern>/init_servlet</url-pattern>
</servlet-mapping>

WEB.XML在你的tomcat/webapp/你的目录/WEB-INF/下..
或者复制tomcat/webapp/ROOT/WEB-INF/下的,,做一下修改就行了.
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

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

类别

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

说明

0/200

提交
取消

辅 助

模 式