尼玛,老子郁闷了。自学了点servlet 写了简单的连接sql server2005的例子,老是报错。
最后花了2个小时,总结一下经验:
=====================================
环境:tomcat-6.0 JCreator编辑器
sql server 2005
1. 准备4个jar包,msbase.jar, mssqlserver.jar, msutil.jar, sqljdbc.jar(sqlserver2005驱动包,微软官网有)
COPY到以下目录,D:\tomcat6\apache-tomcat-6.0.35\lib
2. 配置SQL SERVER 2005 TCP/IP登录,详见:http://blog.csdn.net/indexman/article/details/8502862
3. 修改SQL SERVER 2005 中"sa" 用户密码,注意密码要复杂点(字母+特殊字符+数字,如:dylan$123),并启用该用户:
4 .配置以SQL Server 和Windows身份验证模式, 并测试以sa登录:
5. 配置完以后,贴出以下示例代码:
package com.dylan;
import javax.servlet.http.*; import java.io.*; import java.sql.*; public class LoginProcess extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res){ Connection ct = null; Statement sm = null; ResultSet rs = null; try{ //receive username&password String name = req.getParameter("username"); String pass = req.getParameter("password"); //check the username&password Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); ct = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=xudb","sa","admin$123"); sm = ct.createStatement(); rs = sm.executeQuery("select top 1 * from users where username='"+ name +"' and password='"+ pass +"'"); if(rs.next()) { PrintWriter pw = res.getWriter(); pw.println("Error username or password!"); HttpSession hs = req.getSession(true); hs.setMaxInactiveInterval(10); hs.setAttribute("pass","ok"); res.sendRedirect("wel?username="+name+"&password="+pass); } else{ PrintWriter pw = res.getWriter(); //pw.println("Error username or password!"); res.sendRedirect("login"); } } catch(Exception ex){ ex.printStackTrace(); } finally{ try{ if(rs!=null){ rs.close(); } if(sm!=null){ sm.close(); } if(ct!=null){ ct.close(); } } catch(Exception ex){ ex.printStackTrace(); } } } public void doPost(HttpServletRequest req, HttpServletResponse res){ this.doGet(req, res); } }
present by dylan.