2016-10-07 48 views
1

コードスニペットを把握カント: をボタンクリックで、のActionEventが呼び出されますoracle 10gデータベースからデータをフェッチしているときにjavaの列索引エラーが無効です。いただきました!間違っ

public void actionPerformed(ActionEvent e) 
{ 
Function f = new Function(); 

機能は、私はデータベースとの接続を確立するために使用されている入れ子になったクラスです。 機能クラスのコードスニペットも最後に提供されています。

ResultSet rs = null; 
String Cid ="cust_id"; 
String Pno="cust_phone"; 
String cat="cust_cat"; 
String start_date="st_date"; 
String Adv_amt="adv"; 
String Adv_end="end_date"; 
String Address="addr"; 

t2は、私が顧客名の入力に使用したテキストフィールド名です。この顧客名をPKとして使用して、その顧客に関する他のすべてのデータをDBから取得したいと考えています。ここで

rs=f.find(t2.getText()); 
try{ 
    if(rs.next()) 
    { 
     t1.setText(rs.getString("cust_id")); 
     t3.setText(rs.getString("cust_phone")); 
     t4.setText(rs.getString("cust_cat")); 
     t5.setText(rs.getString("st_date")); 
     t6.setText(rs.getString("adv")); 
     t7.setText(rs.getString("end_date")); 
     t8.setText(rs.getString("addr")); 
    } 
    else 
     JOptionPane.showMessageDialog(null,"No data for this name"); 
} 
catch(Exception ex) 
{ 
    JOptionPane.showMessageDialog(null,ex.getMessage()); 
} 
} 

は、メインクラス内で入れ子になったクラスの関数のコードスニペットです:

class Function{ 
Connection con=null; 
ResultSet rs= null; 
PreparedStatement ps = null; 
public ResultSet find(String s) 
{ 
    try 
    { 
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); 
    con = DriverManager.getConnection("jdbc:oracle:thin:@Localhost:1521:xe","system","qwerty"); 
    ps= con.prepareStatement("Select * from gkkdb where cust_name='?'"); 

    ps.setString(1,s); 

    rs= ps.executeQuery(); 
    } 
    catch(Exception ex) 
    { 
     JOptionPane.showMessageDialog(null, ex.getMessage()); 
    } 
     return rs; 
} 
} 

問題を見つけ出す助けてください。

答えて

2

パラメータプレースホルダー?を一重引用符で囲まないでください。

この:

ps = con.prepareStatement("Select * from gkkdb where cust_name='?'"); 

を使用すると、単一引用符で囲む場合?がプレースホルダとして認識されません

ps = con.prepareStatement("Select * from gkkdb where cust_name = ?"); 

でなければなりません。

0

バインド変数をソートすると、すぐに問題が解決されます。

選択する列を明示的に指定する必要があります(BLOB列を後で追加する可能性があります)ので、正しい順序で取得できます(誰かがテーブルの作成を変更する可能性があります)別のDBインスタンスで実行する前にスクリプトを実行すると、名前で列を参照していますが、異なる順序は位置インデックスを使用していた場合にのみ影響します)。他の回答の再上

同上:バインド変数(すなわち、引用符なし)

プラス、あなたのDBAを頼む、良いアイデアになることはありません「SELECT * FROM」。

もちろん、あなたのコードはもちろんですが、完了するとすぐにリソース(Connection、Statement、ResultSet)を解放してください。 Java 7 try-with-resourcesを使用してください。

関連する問題