简体   繁体   English

带有MS SQL Server 2008的Java Eclipse

[英]Java Eclipse with MS SQL server 2008

I started learning c# with the use of MS SQL server 2008, I'm just wondering if I could implement the 3 layered in jsp? 我从使用MS SQL Server 2008开始学习c#,我只是想知道是否可以在jsp中实现3层?

I will have my Data access layer where my connections and methods like (add,delete,view,update) and so on with the Business logic and for the UI. 我将拥有我的数据访问层,在这里我的连接和方法(如(添加,删除,查看,更新)等)以及业务逻辑和UI。

I tried to do it but it can't display the output. 我尝试这样做,但是无法显示输出。 I tried a simple one of adding then viewing the added ones. 我尝试了一种简单的添加方法,然后查看添加的内容。 (No business logic yet) (尚无业务逻辑)

Here is my code: 这是我的代码:

public class DAL { 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;  
}

Here is my page where it add the products from the user (i just cut the other parts of html) 这是我在其中添加用户产品的页面(我只是剪切了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>

The errors says java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver but I have in my classPath the library and I tried not to have a 3 tier just for testing purposes but yet it still not working. 错误显示java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver但是我在classPath中拥有该库,并且我尝试不具有仅用于测试目的的3层,但仍然无法正常工作。 The return is Null and classnotfoundexception. 返回值为Null和classnotfoundexception。 Any kind of help would be appreciated. 任何帮助将不胜感激。

Multiple issues in your code: 您的代码中存在多个问题:

  • The addProduct() call is missing an pst.executeUpdate() method on the statement. addProduct()调用在该语句上缺少pst.executeUpdate()方法。 So, the insert will never be run. 因此,插入将永远不会运行。

  • The viewProduct() call is not closing the obtained ResultSet , this results in dangling resources in the JDBC driver and possibly even on the SQL-server. viewProduct()调用没有关闭获得的ResultSet ,这导致JDBC驱动程序中甚至是SQL服务器上的资源悬空。

  • You can manage all calls using one connection, no need to open a new one every run. 您可以使用一个连接管理所有呼叫,而无需每次运行都打开一个新的连接。 Besides that, you are not closing the connections after use. 除此之外,使用后您不会关闭连接。 You should use the new Java syntax for try-with-resources or add a finally block: 您应该将新的Java语法用于try-with-resources或添加一个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); } } 

The general approach is very hackish. 通用的方法非常骇人听闻。 If this is to be a JSP based application, you should consider a connection pool instead of handling the connections on a per call basis. 如果这是基于JSP的应用程序,则应考虑使用连接池,而不是基于每个调用来处理连接。 The connection pool is configured as a Datasource in your web.xml and needs to be configured according to the container you are using (Tomcat, Jetty, ...). 连接池在web.xml中配置为数据源,需要根据您使用的容器(Tomcat,Jetty等)进行配置。

If you are using a container datasource, you will draw the connection from the datasource, not from the JDBC driver directly. 如果使用的是容器数据源,则将从数据源绘制连接,而不是直接从JDBC驱动程序绘制连接。 Otherwise, you should consider a connection pool inside your application, that provides a ready-made connection to you on request. 否则,您应该考虑应用程序内部的连接池,该连接池可应要求为您提供现成的连接。

Having said this: 话虽如此:

Where do you place the jar file for the SQL driver? 您将SQL驱动程序的jar文件放在哪里? The way you call it, it should be in the WEB-INF/lib folder of your web application. 调用方式应位于Web应用程序的WEB-INF/lib文件夹中。

First thing to make sure is that the sqlserver library is correctly set in the build path. 首先要确保的是在构建路径中正确设置了sqlserver库。 To access/update/delete entries from your database, try the following: 要访问/更新/删除数据库中的条目,请尝试以下操作:

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();

    }

If the ms sqlserver library is set correctly, this should work for you too. 如果ms sqlserver库设置正确,这也应该为您工作。 Hope it helps... 希望能帮助到你...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM