dポイントプレゼントキャンペーン実施中!

txt1.setText(15,200)

btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

try{

// **接続情報**
String drv = "org.postgresql.Driver";
String url = "jdbc:postgresql:postgres";
String usr = "postgres";

// **DBへの接続、問合せ**
Class.forName(drv);
Connection cn = DriverManager.getConnection(url, usr, pw);

Statement st = cn.createStatement();
String qry1 = "INSERT INTO getuji (数字) VALUES ( "+ txt1.getText() + ");";
st.executeUpdate( qry1 );

// **DB切断**
st.close();
cn.close();

}

catch(Exception f){f.printStackTrace();}

}
});

txt1にカンマの付いている数字を入れるとエラーが出てしまいます。
カンマがなければエラーが起きないのですが何か良い方法はないでしょうか?
DBのgetuji表のテーブル(数字)のデータ型はintegerです。なのですがこれを変えた方がいいのでしょうか?
わかる方がいらっしゃいましたらよろしくお願いします。

A 回答 (2件)

拙者なら、txt1にメソッドを追加して、



> String qry1 = "INSERT INTO getuji (数字) VALUES ( "+ txt1.getText() + ");";

String qry1 = "INSERT INTO getuji (数字) VALUES ( "+ txt1.getInt() + ");";
とします。

getInt()の中は、
----------------------------------------------------------------------
  public int getInt() {
    String a = null;
    String b = null;
    Integer c = null;
    int d = 0;
    
    a = getText();
    
    if (a == null || a.equals("")) {
      return 0;
    }
    
    b = a.replace(",", "");  // カンマ除去
    
    try {
      c = Integer.parseInt(b);
      d = c.intValue();
    } catch (NumberFormatException ex) {
      d = 0;
    }
    
    return d;
  }
----------------------------------------------------------------------
のような感じでよいんじゃないかな。

そう言う話じゃなくて?
    • good
    • 0
この回答へのお礼

ありごとうございます!!こんなやり方があったんですね~。
getInt()なんてものがあるなんて。。。もっと勉強しないと、ですね。
どうもありがとうございました。

お礼日時:2008/10/31 13:57

DBのデータ型を文字型にすればOKです。


ただ、数値項目なので数値型にした方が綺麗です。(一般的)
ですので、
登録前にカンマを取り除き、取得(表示)時にはカンマ編集する、というの定石手段です。
YanchさんのようにTextFieldを拡張するのもあり(その方がスッキリ)ですが、
StringUtilクラスのようなものを作成し、
登録前に、deleteComma()メソッドを呼び出し、
取得(表示)時にgivingComma()を使用する
いかがでしょうか?

String qry1 = "INSERT INTO getuji (数字) VALUES ( "+ StringUtil.deleteComma(txt1.getText()) + ");";

<参考ソース>
import java.text.DecimalFormat;

public class StringUtil {

public static String givingComma(String target) {

DecimalFormat formatter = new DecimalFormat("#,###");
return formatter.format(deleteComma(target));
}

public static int deleteComma(String target) {

int rtnValue = 0;

if (target == null || target.equals("")) {
return rtnValue;
}

String work = target.replaceAll(",", "");

try {

rtnValue = Integer.parseInt(work);

} catch (NumberFormatException ex) {
return rtnValue;
}

return rtnValue;
}
}

この回答への補足

ありがとうございます。カンマだけをつけたり消したりできるんですね・・・・ちょっとカンマと違うのですがdeleteComma()やgivingComma()は、

MaskFormatter mf1 = null;

try{
mf1 = new MaskFormatter("###:##");
}catch(ParseException pe){}

final JFormattedTextField txt27 = new JFormattedTextField(mf1);

としている「:」に対しても同様のことができるのでしょうか?最初の質問と少しずれているのですが、お聞きしてよいでしょうか・・・新しく上げた方がいいのかな・・・?

補足日時:2008/10/31 14:03
    • good
    • 0
この回答へのお礼

「:」に関しては自己解決できました!!どうもありがとうございました!

お礼日時:2008/10/31 23:03

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!