让我纠结了很久的JDBC !

     用Java EE的人都知道了,当需要连接到数据库的时候必定需要用到JDBC。终于,今天我也遇到了这个问题。对于像我这样的初学者来说,要搞定这个JDBC还是有一定困难的。至少我自己就用了整整一个下午加一个晚上才搞定这个东西,比较囧。不说废话了,直接把方法写下来,即方便自己以后查看,另一方面也方便像我这样的初学者查阅。

     首先,我们必须下载JDBC Driver(我用的是SqlServer 2008),可以到微软的站上去下载,这是下载地址:http://www.microsoft.com/downloads/details.aspx?FamilyID=99b21b65-e98f-4a61-b811-19912601fdc9&displaylang=zh-cn   下载我们将得到一个自解压的压缩包,随便找个目录把这个压缩包解压。注意:在解压的目录名字中不要存在空格(在配置环境变量是有用)。据微软说,这个环境变量的设置中间如果存在空格有可能导致环境变量设置失败,谨慎起见,我们还是将jdbc解压到没有空格的目录里。在解压目录下,我们会看到sqljdbc_2.0\chs,在chs下面,我们可以看到两个jar,一个时sqljdbc.jar,另一个是sqljdbc4.jar。接下来,我们把这个jar加到环境变量的CLASSPATH中,如:

捕获

这个是我的环境变量的设置。注意:sqljdbc.jar 和sqljdbc4.jar包含一个到环境变量就可以了,不要将两个都加到CLASSPATH中。

仅仅在系统的环境变量中添加CLASSPATH还不够,还需要在IDE中添加环境变量。我是用NetBeans的,添加情况如下:首先在项目上右击,选择属性:

image

在库中添加sqljdbc4.jar或者sqljdbc.jar

OK配置完成,接下来就是测试了。在SqlServer 2008中新建数据库名为TestDataBase,在数据库中添加Users表,Users表中有UserId,UserName两项,在表内填入一些数据。

如下式测试代码:

  1: /*
  2:  * To change this template, choose Tools | Templates
  3:  * and open the template in the editor.
  4:  */
  5: 
  6: package com.mlp;
  7: 
  8: import com.mlp.classes.*;
  9: import java.io.IOException;
 10: import java.io.PrintWriter;
 11: import javax.servlet.ServletException;
 12: import javax.servlet.http.HttpServlet;
 13: import javax.servlet.http.HttpServletRequest;
 14: import javax.servlet.http.HttpServletResponse;
 15: 
 16: /**
 17:  *
 18:  * @author Administrator
 19:  */
 20: public class Servlet extends HttpServlet {
 21:    
 22:     /** 
 23:      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 24:      * @param request servlet request
 25:      * @param response servlet response
 26:      * @throws ServletException if a servlet-specific error occurs
 27:      * @throws IOException if an I/O error occurs
 28:      */
 29:     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
 30:     throws ServletException, IOException {
 31:         response.setContentType("text/html;charset=UTF-8");
 32:         PrintWriter out = response.getWriter();
 33:         try {
 34:             String id = "123";
 35:             String name="mlp";
 36:             UserBean ub = new UserBean();
 37:             if(ub.CheckUser(id, name))
 38:             {
 39:                 out.println("合法用户。");
 40:             }
 41:             else
 42:             {
 43:                 out.println("非法用户。");
 44:             }
 45:         } finally { 
 46:             out.close();
 47:         }
 48:     } 
 49: 
 50:     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
 51:     /** 
 52:      * Handles the HTTP <code>GET</code> method.
 53:      * @param request servlet request
 54:      * @param response servlet response
 55:      * @throws ServletException if a servlet-specific error occurs
 56:      * @throws IOException if an I/O error occurs
 57:      */
 58:     @Override
 59:     protected void doGet(HttpServletRequest request, HttpServletResponse response)
 60:     throws ServletException, IOException {
 61:         processRequest(request, response);
 62:     } 
 63: 
 64:     /** 
 65:      * Handles the HTTP <code>POST</code> method.
 66:      * @param request servlet request
 67:      * @param response servlet response
 68:      * @throws ServletException if a servlet-specific error occurs
 69:      * @throws IOException if an I/O error occurs
 70:      */
 71:     @Override
 72:     protected void doPost(HttpServletRequest request, HttpServletResponse response)
 73:     throws ServletException, IOException {
 74:         processRequest(request, response);
 75:     }
 76: 
 77:     /** 
 78:      * Returns a short description of the servlet.
 79:      * @return a String containing servlet description
 80:      */
 81:     @Override
 82:     public String getServletInfo() {
 83:         return "Short description";
 84:     }// </editor-fold>
 85: 
 86: }
 87: 
其中,UserBean的代码如下:
  1: /*
  2:  * To change this template, choose Tools | Templates
  3:  * and open the template in the editor.
  4:  */
  5: 
  6: package com.mlp.classes;
  7: 
  8: import java.sql.*;
  9: /**
 10:  *
 11:  * @author Administrator
 12:  */
 13: public class UserBean
 14: {
 15:     private String UserId;
 16:     private String UserName;
 17: 
 18:     public UserBean()
 19:     {
 20:     }
 21: 
 22:     public boolean CheckUser(String id,String name)
 23:     {
 24:         boolean flag = false;
 25:         Connection conn = this.GetConnection();
 26:         PreparedStatement ps = null;
 27:         ResultSet rs = null;
 28:         try
 29:         {
 30:             ps = conn.prepareStatement("SELECT [UserId] FROM [Users] WHERE [UserName]='" + name + "'");
 31:             rs = ps.executeQuery();
 32:             if(rs.next())
 33:             {
 34:                 if(id.equals(rs.getString(1)))
 35:                 {
 36:                     System.out.println("Legal");
 37:                     flag = true;
 38:                 }
 39:                 else
 40:                 {
 41:                     System.out.println("ILLegal");
 42:                 }
 43:             }
 44:             else
 45:             {
 46:                 System.out.println("Can not find the user");
 47:             }
 48:         }
 49:         catch(Exception ex)
 50:         {
 51:             ex.printStackTrace();
 52:         }
 53:         finally
 54:         {
 55:             if(rs != null)
 56:             {
 57:                 try
 58:                 {
 59:                     rs.close();
 60:                     rs = null;
 61:                 }
 62:                 catch(Exception ex)
 63:                 {
 64:                     ex.printStackTrace();
 65:                 }
 66:             }
 67:             if(ps != null)
 68:             {
 69:                 try
 70:                 {
 71:                     ps.close();
 72:                     ps = null;
 73:                 }
 74:                 catch(Exception ex)
 75:                 {
 76:                     ex.printStackTrace();
 77:                 }
 78:             }
 79: 
 80:             if(conn != null)
 81:             {
 82:                 try
 83:                 {
 84:                     conn.close();
 85:                     conn = null;
 86:                 }
 87:                 catch(Exception ex)
 88:                 {
 89:                     ex.printStackTrace();
 90:                 }
 91:             }
 92:         }
 93:         return flag;
 94:     }
 95: 
 96:     public Connection GetConnection()
 97:     {
 98:         Connection conn = null;
 99:         try
100:         {
101:             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
102:             conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;database=TestDataBase;user=sa;password=718608");
103:         }
104:         catch(Exception ex)
105:         {
106:             ex.printStackTrace();
107:         }
108:         
109:         return conn;
110:     }
111: }
112: 
原文地址:https://www.cnblogs.com/malloc/p/1693287.html