0

I have configured mysqlDatasource in tomcat from this and this. I have followed steps specified there. I have used following lines of code

class DataConnection {
    private static DataSource dataSource;

    public DataConnection() {
        try {
            Context ctx = new InitialContext();
            dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/test");
        } catch (NamingException e) {
           e.printStackTrace(); 
        }
    }

    public static Connection getConnection() throws SQLException {
        new DataConnection();
          Connection con=dataSource.getConnection();
          return con;
    }
}

But I still get a NullPointerException when connecting database.

  1. Copied jar file into mysql/lib folder
  2. Creating context.xml file and mention connection property.
  3. In WEB-INF/web.xml I have mentioned

    jdbc/db javax.sql.DataSource

What am I doing wrong?

Note:I have created context.xml and mention the connection property. Finally manually copied into META-INF/context.xml.

Community
  • 1
  • 1
Ami
  • 4,241
  • 6
  • 41
  • 75
  • check in the try block by putting breakpoint weather it is created or not.I think the problem in "ava:comp/env/jdbc/test" – PSR Feb 27 '13 at 05:12
  • yes.i have checked datasource value is null. – Ami Feb 27 '13 at 05:14
  • 3
    add e.printStackTrace(); in the catch block - I'm guessing that an exception is being thrown, but you don't see it because your catch block is empty. The exception should tell you what's wrong – GreyBeardedGeek Feb 27 '13 at 06:22

1 Answers1

0

Try instance of InitialContex instead of Context and print sth

public DataConnection() {
            try {
                InitialContext ctx = new InitialContext();
                dataSource = (DataSource)ctx.lookup(dataSource name);
            } catch (NamingException e) {
                    e.printStackTrace();
            }
        }
mykey
  • 575
  • 2
  • 10
  • 24
  • I dont know either you understand question or not.Context ctx = new InitialContext();Its working fine.when control comes next line it return null values only.datasource value is null. – Ami Feb 27 '13 at 06:14
  • what is the exception? after printing – mykey Feb 27 '13 at 06:26