Sal-laS
Sal-laS

Reputation: 11639

NullPointerException when run executeQuery(sql)

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

Upvotes: 1

Views: 5542

Answers (3)

BobTheBuilder
BobTheBuilder

Reputation: 19284

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

Upvotes: 2

Shurmajee
Shurmajee

Reputation: 1047

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

Upvotes: 0

Vikdor
Vikdor

Reputation: 24124

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

Upvotes: 0

Related Questions