简体   繁体   English

如何建立JDBC连接

[英]How to make JDBC connectivity

I am using the follwing class as my connection manager to make DB connectvity through datasource. 我正在使用以下类作为我的连接管理器,以通过数据源进行数据库连接。 The problem is that when I invoke this class through my DAOImpl class it is returning null. 问题是,当我通过DAOImpl类调用此类时,它返回null。

private static DataSource dataSource;
private static Connection connection;

private ConnectionFactory() {
    System.out.println(" ConnPoolFactory cons is called ");
}

public static synchronized Connection getConnection() throws SQLException {

    try {

        if (connection == null) {
            Context ctx = new InitialContext();
            Context envContext = (Context) ctx.lookup("java:/comp/env");


            dataSource = (DataSource) envContext.lookup("jdbc/myoracle");
            connection = dataSource.getConnection();
        } else {
            return connection;
        }

    } catch (NamingException e) {
        e.printStackTrace();
    }
    System.out.println(connection);
    return connection;
    //System.out.println(connection);

} 
  • I am able to make this class work if I use DriverManager for conectivity. 如果我将DriverManager用于连接性,则可以使此类工作。
  • I am able to achieve JDBC connectvity through servlet class using a DataSource . 我可以使用DataSource通过servlet类实现JDBC connectvity。

But with the above code I get the following exception: 但是使用上面的代码,我得到以下异常:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: javax.naming.NoInitialContextException:需要在环境或系统属性中或作为applet参数或在应用程序资源文件中指定类名称:

the following is my context.xml 以下是我的context.xml

<Resource auth="Container" 
          driverClassName="oracle.jdbc.OracleDriver" 
          name="jdbc/myoracle" 
          password="password" 
          type="javax.sql.DataSource" 
          url="jdbc:oracle:thin:@10.49.116.42:1521:DBNAME" 
          username="username"/>

我认为您错过了用于数据库连接的主机和端口

sample code for connectivity 连接的示例代码

 public static Connection Connect(){


    try {

        Class.forName("oracle.jdbc.driver.OracleDriver");

    } catch (ClassNotFoundException e) {

        System.out.println("Where is your Oracle JDBC Driver?");
        e.printStackTrace();
        return null;

    }

    System.out.println("Oracle JDBC Driver Registered!");

    Connection connection = null;

    try {

        connection = DriverManager.getConnection(
                "YOUR JDBC URL", "USERNAME",
                "PASSWORD");

    } catch (SQLException e) {

        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return null;

    }



    return connection;

}

You write like this jdbc connectivity code 您可以这样编写jdbc连接代码

String url = "jdbc url" + "databaseName;userName;password;";

        try 
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(url);
        } 
        catch (ClassNotFoundException cnfex) 
        {
            cnfex.printStackTrace();
        }

I am really not able to understand what you are trying to ask...But if you want JDBC connectivity here is a way : 我真的不明白您要问的是什么...但是如果您想要JDBC连接,可以采用以下方法:
1.You have to Install JDBC driver for that RDBMS that you are using...if you are using any IDE then there is no need to install it separately... 1.您必须为正在使用的RDBMS安装JDBC驱动程序...如果使用任何IDE,则无需单独安装它...
2.you have to tell the computer where the Driver is stored 2.您必须告诉计算机驱动程序的存储位置
i>You have to set environment variables i>您必须设置环境变量 在控制面板中搜索环境变量

After that you are ready to connect your java code with database 之后,您就可以将Java代码与数据库连接了

try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:port_number/Database name","root","password");

you have to enter the Database name,port number and password for the database you are using NOTE : here database is MySql.For other RDBMS the url will be different. 您必须输入要使用的数据库的数据库名称,端口号和密码。 注意:此处的数据库为MySql。对于其他RDBMS,URL将不同。 Hope this helps 希望这可以帮助

You mentioned about context.xml. 您提到了context.xml。 So, assuming that you are using Apache Tomcat container for JDBC connectivity. 因此,假设您使用Apache Tomcat容器进行JDBC连接。

So, to me problem seems to be due below possibilities: 因此,对我来说问题似乎是由于以下可能性造成的:

  1. If two resources with the same name both declared in the context.xml files under the web application's META-INF directory and in the $CATALINA_BASE/conf directory, then the internal version takes precedence. 如果两个相同名称的资源都在Web应用程序的META-INF目录下的context.xml文件和$ CATALINA_BASE / conf目录中声明,则内部版本优先。 Please check if you have context.xml under META-INF and you have done correct config in CATALINA_BASE/conf server.xml. 请检查META-INF下是否有context.xml,并且在CATALINA_BASE / conf server.xml中完成了正确的配置。 If so, update context.xml file under META-INF. 如果是这样,请更新META-INF下的context.xml文件。

Note from Apache website: Tomcat specific resource configuration is entered in the elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file (META-INF/context.xml). 来自Apache网站的注释:在$ CATALINA_BASE / conf / server.xml或最好是每个Web应用程序上下文XML文件(META-INF / context.xml)中可以指定的元素中输入Tomcat特定的资源配置。 。

  1. Note that the resource name (as mentioned in your code, jdbc/myoracle) must match the value specified in the web application deployment descriptor. 请注意,资源名称(如您的代码jdbc / myoracle中所述)必须与Web应用程序部署描述符中指定的值匹配。 Link explains how to: https://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html 链接说明了如何: https : //tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html

Note: If a resource has been defined in a element it is not necessary for that resource to be defined in /WEB-INF/web.xml. 注意:如果已在元素中定义了资源,则不必在/WEB-INF/web.xml中定义该资源。 However, it is recommended to keep the entry in /WEB-INF/web.xml to document the resource requirements for the web application. 但是,建议将该条目保留在/WEB-INF/web.xml中,以记录Web应用程序的资源要求。 So, you can try removing Oracle JDBC entry in web.xml and evaluate first if things work. 因此,您可以尝试删除web.xml中的Oracle JDBC条目,然后首先评估是否可行。 Then put correct entry. 然后输入正确的内容。

  1. If you like to test JDBC connectivity without using container, you could use RMI registry. 如果要在不使用容器的情况下测试JDBC连接,则可以使用RMI注册表。 Post below has example for MYSQL which you can modify for Oracle to test: javax.naming.NoInitialContextException with mysql DataSource 下面的帖子有MYSQL的示例,您可以修改该示例以供Oracle测试: javax.naming.NoInitialContextException与mysql数据源

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

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