Question

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); 
   }
Was it helpful?

Solution

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; 
    }

OTHER TIPS

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).

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();
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top