GlassFish JDBC连接池

时间:2015-01-05 05:36:40

标签: java odbc connection-pooling pool jdbc-odbc

我正在尝试为我的网络应用程序建立连接池,但不知道如何使用sql server设置基础知识

主要问题:什么是资源类型(写什么),classname,driverclass name?

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    String str="SELECT * from Book";
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        try {
            Connection con = DriverManager.getConnection("jdbc:odbc:lol","Sar\\KILLER_GUY",null);
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery(str);
            System.out.println("SalesPerson Id: ");
            while(rs.next())
            {
                String id= rs.getString("Add");
            System.out.println(id);
            }
            con.close();
        }
    catch(SQLException e)
    {

    }

1 个答案:

答案 0 :(得分:9)

您需要在GlassFish中设置连接池,然后通过JNDI(Java命名和目录接口 - 目录服务的Java API)访问连接池数据源。请参阅this step by step tutorial,其中提供了以下大纲的详细信息:

  1. 打开JDBC连接池列表

    在Glassfish管理面板中,使用页面左侧的导航菜单打开JDBC Connections Pool列表(Resources-> JDBC-> Connections Pools)。在JDBC Connections Pool中,单击New ...以创建新的JDBC连接池。

  2. 创建新的JDBC连接池

    在“新建JDBC连接池”对话框中,指定池的名称。请务必指定正确的“资源类型”,然后单击“下一步”。

  3. 指定数据源类名( com.microsoft.sqlserver.jdbc.SQLServerDataSource

    在下一页上,指定数据源类名。类名当然是特定于驱动程序的。请查阅您的驱动程序文档以找到合适的类。单击“完成”以创建JDBC连接池。

  4. 编辑连接池

    创建JDBC连接池后,您可以返回并添加/编辑JDBC连接URL,用户名,密码等属性。

  5. 创建JDBC资源

    最后,您需要创建一个可在Web应用程序中引用的新JDBC资源(Resources-> JDBC-> JDBC Resources)。

  6. 创建连接

    创建连接池后,您可以在Web应用程序(例如servlet或JSP)中使用它,如下所示:

  7. // Look up the connection pool data source
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("Your JNDI Name here");
    
    // Get a database connection
    java.sql.Connection conn = ds.getConnection();
    try {
      // Do something with the connection
    } finally {
      // Close connection so it can be released back to the pool!
      conn.close();
    }