1

I have simple query in Java to run in SQL SERVER 2008. When it reaches to

rs = stmt.executeQuery(sql); it gives me java.lang.NullPointerException

1-I use jtds driver to connect my code to database.

2-When I execute the query directly in database it works.

3-To make code short and easy to understand I omitted the Try-Catch

    public class DataBases 
    {

        private  Connection link;
        private  java.sql.Statement  stmt;
        public    ResultSet rs;

        public DataBases() 
        {    

            Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
            String connectionUrl = "jdbc:jtds:sqlserver://localhost:1433;databaseName=DB;integratedSecurity=true";
            Connection link = DriverManager.getConnection(connectionUrl);


        }


        public ResultSet select(String sql)
        {
         rs = stmt.executeQuery(sql);                        
             return rs; 
        }
}



    public static void main(String[] args)
    {   

        DataBases s=new DataBases();      
        String sql="SELECT * FROM [DB].[dbo].[quantities] ";                       
        ResultSet rs=s.select(sql); 
   }
1
  • Where do you instantiate stmt? Commented Feb 19, 2013 at 7:36

3 Answers 3

2

You need to instantiate stmt somewhere (in the constructor or inside select function)

You can also move stmt field to be a variable of select function.

    public ResultSet select(String sql)
    {
         Statement  stmt = link.createStatement();
         rs = stmt.executeQuery(sql);                        
         return rs; 
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Your select method should look like this, just to get your code working:

    public ResultSet select(String sql)
    {
         stmt = link.createStatement();
         rs = stmt.executeQuery(sql);                        
         return rs; 
    }

You need to look at a good tutorial on how to perform a jdbc operation without leaking resources (like connections here).

Comments

0

As the stmt object reference is not pointing to any object you are getting an NPE. try..

public DataBases() 
        {    

            Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
            String connectionUrl = "jdbc:jtds:sqlserver://localhost:1433;databaseName=DB;integratedSecurity=true";
            Connection link = DriverManager.getConnection(connectionUrl);
            Statement stmt = link.createStatement();
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.