2017-06-08 3 views
1

Connection接続オブジェクトを取得するために呼び出されたコンストラクタでオブジェクトがnullではありませんが、オブジェクト私はnullになっています。接続オブジェクトは接続オブジェクトを取得するために呼び出されたが、他の関数ではNULLを取得しています。

package shoppings; 

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException;` 
import Filehandling.MyConnection; 

public class Product { 

    public static void main(String args[]){ 
     String sql = "select ProductID, ProductName from products "; 
     ProductDetail ub = new ProductDetail(); 
     ub.getProductDetail(); 
    } 
} 

    class ProductDetail{ 
    Connection con=null; 
    PreparedStatement st; 
    ResultSet rs; 

    public ProductDetail(){ 
     MyConnection mycon = new MyConnection(); 
     Connection con = mycon.getConnObject(""); 
     System.out.println(con); 
     //o/t [email protected] 
    } 

    public void getProductDetail(){ 

     System.out.println(con); 
     //o/t null 

    } 

} 

答えて

0

コンストラクタ内の変数をインスタンス変数に設定していません。これを試してみてください:

public ProductDetail(){ 
    MyConnection mycon = new MyConnection(); 
    con = mycon.getConnObject(""); 
    System.out.println(con); 
} 
0

もちろんはい、ここにあなたの接続オブジェクト:

public ProductDetail(){ 
    MyConnection mycon = new MyConnection(); 
    Connection con = mycon.getConnObject(""); 
    System.out.println(con); 
} 

がローカルメソッドProductDetailsにスコープされていないと、そのメソッドが実行された後はもはやavaliableになりますので、それが影を作っていますクラスの接続部材を介して

が代わりに行います。

public ProductDetail(){ 
    MyConnection mycon = new MyConnection(); 
    con = mycon.getConnObject(""); 
    System.out.println(con); 

} 
0

をコンストラクタヨーヨーでuがConnection conローカル変数を宣言すると、あなたはそれをインスタンス化:

public ProductDetail(){ 
     ... 
    Connection con = mycon.getConnObject(""); 
     ... 
} 

しかし、このローカル変数がConnection con変数フィールドは異なる変数であるが、ここに宣言:

class ProductDetail{ 
.... 
    Connection con=null; 
} 

だからそのうちの一つが変化しない割り当てますもう一方の値。

Connection conフィールドの値を設定する場合は、コンストラクターに別の変数を宣言する必要はありません。
ただ、インスタンスフィールドに新しい作成Connectionを割り当てるために、あなたのコンストラクタを変更します。

con = new MyConnection().getConnObject(""); 
関連する問題