【问题标题】:Java Eclipse with MS SQL server 2008带有 MS SQL Server 2008 的 Java Eclipse
【发布时间】:2015-04-08 14:10:13
【问题描述】:

我开始使用MS SQL server 2008学习c#,我只是想知道我是否可以在jsp中实现3层?

我将拥有我的数据访问层,其中我的连接和方法(如(添加、删除、查看、更新)等)与业务逻辑和 UI 一起使用。

我尝试这样做,但它无法显示输出。我尝试了一个简单的添加然后查看添加的。 (还没有业务逻辑)

这是我的代码:

公共类 DAL {

public static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static String connectionURL = "jdbc:sqlserver://localhost; database = Sample; Integratedsecurity = true";


public void addProduct(String productName){
    try {
        Class.forName(driver);
        Connection con = DriverManager.getConnection(connectionURL);

            String sql = "Insert into Products values (?)";
            PreparedStatement pst = con.prepareStatement(sql);
            pst.setString(1, productName);
            pst.closeOnCompletion();
            pst.close();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public ResultSet viewProduct(){
    ResultSet rs = null;
    try {
        Class.forName(driver);
        Connection con = DriverManager.getConnection(connectionURL);
        String sql = "Select * from Products";

        PreparedStatement pst = con.prepareStatement(sql);
        rs = pst.executeQuery();

        while(rs.next()){
            rs.getInt(2);
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return rs;  
}

这是我添加用户产品的页面(我只是剪掉了 html 的其他部分)

<%!
    DAL d = new DAL();
%>

<body>
<% 
    String productName = request.getParameter("productName") != null ?   
        request.getParameter("productName") : "No product has been delivered";
    d.addProduct(productName);
%>
<h1> Product: <%= d.viewProduct() %> </h1>
</body>

错误显示java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver,但我在我的classPath 库中有一个库,我尝试不使用3 层来进行测试,但它仍然无法正常工作。返回为 Null 和 classnotfoundexception。任何形式的帮助将不胜感激。

【问题讨论】:

    标签: java eclipse sql-server-2008


    【解决方案1】:

    您的代码中有多个问题:

    • addProduct() 调用在语句中缺少 pst.executeUpdate() 方法。因此,插入将永远不会运行。

    • viewProduct() 调用不会关闭获得的ResultSet,这会导致 JDBC 驱动程序甚至 SQL 服务器上的资源悬空。

    • 您可以使用一个连接管理所有呼叫,无需每次运行都打开一个新连接。除此之外,您不会在使用后关闭连接。您应该为 try-with-resources 使用新的 Java 语法或添加 finally 块:

       try ( Statement st = connection.prepareStatement(sql); )
       {
           // use the statement here ...
           st.executeUpdate();
       }
       catch(Exception e) {
       }
       // st will be closed here
      
      
      Statement st = null;
      try
      {
         st = connection.prepareStatement(sql);
      }
      catch(Exception e) {
      }
      finally {
          try { 
              if( st != null ) st.close(); 
          } 
          catch (Exception ex) {
               throw new RuntimeException("cannot close statement", ex);
          }
      }
      

    一般的方法是非常骇人听闻的。如果这是一个基于 JSP 的应用程序,您应该考虑一个连接池,而不是基于每个调用处理连接。连接池在你的web.xml中配置为Datasource,需要根据你使用的容器(Tomcat,Jetty,...)进行配置。

    如果您使用的是容器数据源,您将从数据源中提取连接,而不是直接从 JDBC 驱动程序中提取连接。否则,您应该考虑在您的应用程序中使用一个连接池,它会根据您的请求为您提供现成的连接。

    话虽如此:

    您将 SQL 驱动程序的 jar 文件放在哪里?按照您的称呼,它应该位于您的 Web 应用程序的 WEB-INF/lib 文件夹中。

    【讨论】:

    • 对不起,我听不清楚。我还在学习它的基础知识。但据我所知,我创建了一个用户库,我称之为 JDBC 并导入了 jar 文件,即 sqljdbc4.jar。那为什么我会有一个 classnotfoundexception 呢?
    • 您如何运行您的应用程序?因为它是一个 JSP,所以你必须有某种容器。
    • 我正在通过 eclipse、apache tomcat v8 运行我的 Web 应用程序
    • 如果你导出到war文件(伪装的ZIP压缩包),你应该在web-inf/lib文件夹中找到sqljdbc4.jar,如果没有,问题出在您配置类路径的方式。您可能想尝试使用静态类或单元测试来运行您的 DAL。如果这工作正常,那么您有一个部署问题。如果测试应用程序不起作用,您需要先修复它。
    • 在war文件中导出时不存在?我需要将 jar 文件复制并粘贴到我的 Eclipse 中的 web-inf/lib 文件夹中吗?
    【解决方案2】:

    首先要确保在构建路径中正确设置了 sqlserver 库。要访问/更新/删除数据库中的条目,请尝试以下操作:

    Connection conn = null;
    
    Statement stmt = null;
    
    try {
    
        // Register JDBC driver
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    
        conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
    
        stmt = conn.createStatement();
    
        String sql = "Enter your update query";
    
        stmt.executeUpdate(sql);
    
        // Extract all the records to see the updated records
        sql = "Enter your select query";
    
        ResultSet rs = stmt.executeQuery(sql);
    
        while (rs.next()) {
    
            // Retrieve data by column name in your database
            String username = rs.getString("enter relevant column name from database");
    
            int logintries = rs.getInt("enter relevant column name from database");
    
            // Display values to console
            System.out.print("Username : " + username);
    
            System.out.print(", Login Tries : " + logintries);
    
        }
    
        rs.close();
    
        } catch (SQLException se) {
    
            se.printStackTrace();
    
        } catch (Exception e) {
    
            e.printStackTrace();
    
        }
    

    如果 ms sqlserver 库设置正确,这也应该适用于您。希望对你有帮助...

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多