0

postgresqlを使用していて、2つの異なるテーブルにデータを挿入する際に1つの問題が発生しています。

アイデアは、いくつかのデータを挿入しないことtableamizadesであり、それらはいくつかのデータをに挿入しtablenotifyます。基本的に友達リクエストが行われ、そのリクエストに関連付けられた通知があります。

私はこのコードを持っています:

01    @Override
02    public void AddFriends(int userMakesRequest, int userReceivesRequest, boolean TrueOrFalse, boolean TrueOrFalse2) {
03        String notificacao, userMakesRequestName;
04        Connection connection = null;
05        Statement stmt = null;
06        ResultSet rs = null;
07
08        try {
09            Class.forName("org.postgresql.Driver");
10
11            connection = DriverManager.getConnection("jdbc:postgresql:"
12                    + "//localhost:5432/projecto", "postgres", "admin");
13
14            stmt = connection.createStatement();
15            try {
16
17                stmt.executeQuery("INSERT INTO tableamizades (iduser1,iduser2,amigoaceite1,amigoaceite2) VALUES ( "
18                        + userMakesRequest + " , '" + userReceivesRequest + "' , '" + TrueOrFalse + "' , '"
19                        + TrueOrFalse2 + "');");
20                try {
21
22
23                    rs = stmt.executeQuery("SELECT username FROM utilizadores WHERE iduser = '" + userMakesRequest + "';");
24                    rs.next();
25                    userMakesRequestName = rs.getString("username");
26
27                    notificacao = " O utilizador " + userMakesRequestName + " fez-lhe um pedido de amizade";
28
29                    stmt.executeQuery("INSERT INTO tablenotify (iduser,notificacao) VALUES ( " + userReceivesRequest + " , '" + notificacao + "');");
30                    rs.close();
31
32                } catch (SQLException e) {
33                }
34
35            } catch (SQLException e) {
36            }
37            stmt.close();
38
39            connection.close();
40
41        } catch (Exception e) {
42            e.printStackTrace(System.out);
43        } finally {
44            try {
45                connection.close();
46            } catch (Exception e) {
47                e.printStackTrace(System.out);
48            }
49        }

これを行うと、データは挿入されますが、挿入されtableamizadesませんtablenotifytablenotify15行目から19行目と35行目と36行目をコメントアウトすると、上のデータtablenotifyが正しく挿入されるため、データを挿入するためのコードは問題ないことがわかります。

誰かが私が間違っていることを教えてもらえますか?

4

1 に答える 1

3

You have several things wrong:

  • inserting data must be done with executeUpdate(), and not executeQuery()
  • you should learn about prepared statements which would avoid SQL injection attacks and incorrect queries if your parameters contain characters like quotes, which must be escaped.
  • you should not ignore SQLExceptions as you're doing, since they contain the error message which would help identifying the problem. Don't catch those exceptions. If you catch them, throw a runtime exception wrapping them.
于 2012-10-21T11:47:12.823 に答える