连接mysql首先要有驱动mysql-connector-java-5.1.0-bin.jar,该驱动可放置在tomcat安装目录\lib目录下,该附件下载见该文章尾部,下面给出一个具体的Servlet:
package lcy;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import lcy.userEntity;
public class userServlet extends HttpServlet {
public void init(ServletConfig conf) throws ServletException
{
super.init(conf);
}
public void init() throws ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ce)
{
throw new UnavailableException("加载数据库驱动失败!");
}
catch(Exception e)
{
throw new UnavailableException("加载数据库驱动失败!");
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
//获取用户名和密码
HttpSession session = req.getSession(true);
String uid = req.getParameter("txtUserName");
String pwd = req.getParameter("txtUserPwd");
PrintWriter out=res.getWriter();
Connection conn=null;
res.setCharacterEncoding("GB2312");
try
{
String dsn="jdbc:mysql://localhost:3306/test_db?user=root&password=sa&useUnicode=True&characterEncoding=GB2312";
conn = DriverManager.getConnection(dsn);
Statement cmd = conn.createStatement();
String sql = "select oid from tblUser where userID='" + uid +"' and userPwd='" + pwd + "'";
ResultSet rs = cmd.executeQuery(sql);
out.println(uid + "," + pwd );
if(rs.next())
{
/*
String url="/EShop.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req,res);
*/
session.setAttribute("userOID", uid);
res.sendRedirect("index.htm");
}
else
{out.println("<script language='javascript'>alert('" + encoding("user not exists!") + "');history.back(-1);</script>");}
}
catch(SQLException se)
{se.printStackTrace();
}
}//end doPost
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
}
private String encoding(String str)
{
try
{
str = new String(str.getBytes("ISO-8859-1"),"GB2312");
}
catch(UnsupportedEncodingException err)
{
System.out.println("不支持的编码格式:" + err.getMessage());
}
return str;
}
}//end userServlet
下载附件:mysql-connector-java-5.1.0-bin.jar