1

現在、Swing GUI コンポーネントとの間で入出力を実行し、ローカルの Microsoft Access 2007 データベースからこのデータを保存/取得するアプリケーションを Java で作成しています。Text または Memo フィールドに格納される JTextArea からの入力でレコードを更新しようとする場合を除いて、すべてうまくいっています。JTextField からの入力は正常に取得できますが、「SQLException: UPDATE ステートメントの構文エラー」が発生します。JTextArea を使用します。

問題が発生しているコードは次のとおりです。

/* <in_some_method> */
myJTextArea.setText(someString); // the components can have the exact
myJTextField.setText(someString); // same string and still have problems

saveEdit(myTable, myColumn, myJTextField.getText(), myID); // this works fine
saveEdit(myTable, myColumn, myJTextArea.getText(), myID); // this throws an exception
/* </in_some_method> */

/* the update method */
public void saveEdit(String table, String column, String value, long id) {
    String query = "UPDATE " + table + " ";
    query += "SET " + column + " = '" + value + "', "
    query +=  "UpdatedAt = Now() ";
    query += "WHERE ID = " + id;

    try {
        // conn is a working connection to the database
        Statement s = conn.createStatement();

        // execute the query
        s.executeUpdate(query);

        // close open database handle
        s.close();

    } catch (Exception ex) {
        System.err.println(ex);
    }
}

いくつかのこと:

  • データベース内のフィールドのデータ型には存在しないと思います。タイプにメモとテキストの両方を試しましたが、どちらも JTextField で動作し、JTextArea では動作しません。

  • 例外は、既に述べたように、「SQLException: UPDATE ステートメントの構文エラー」です。だから私の問題はデータベーステーブルのレイアウトとは何の関係もないことを知っています。要求されたテーブルと列が存在し、アクセスできます。

誰にもアイデアはありますか?どんな助けでも大歓迎です。

4

2 に答える 2

1

I don't know what someString is, but I'm betting it contains newlines or such, so when setting into a JTextField it will be "flattened" while when setting to the JTextArea it will not. So, when getting, you'll have two different strings, one that will work fine and other that will cause a syntax error.

Whatever the case is, you should escape your strings before saving them in the database, or you run the risk of SQL injection. This will also ensure your method work fine for both components (though the exact string can be still different, for the reason stated above).

于 2012-06-28T03:53:27.913 に答える
1

SQL インジェクションに対して脆弱であるという mgibsonbr に同意します。これは、それらの使用方法に関する別のチュートリアルです

ただし、当面の問題については、テキストフィールドの getText() を使用して取得した文字列が既に機能していることを考えると、JTextArea から getText() を使用して取得した文字列を保存して、それが何であるかを確認しようとしたことがありますか? または、おそらく JTextArea の getText メソッドでトリム関数を呼び出そうとしたので、空のスペースなどはありません.

JTextArea に対して someString が適切に設定されていない可能性があります。

于 2012-06-28T04:04:19.223 に答える