teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

追記

2019/10/29 05:11

投稿

quickquip
quickquip

スコア11314

answer CHANGED
@@ -45,7 +45,7 @@
45
45
  ```python
46
46
  db.c.execute('update twitter_users set comment = ? where name = ?', (name, comment))
47
47
  ```
48
- だとnameとcommentが逆ですからwhere句でヒットしないので0件のupdateで終了する)
48
+ だとnameとcommentが逆ですからwhere句でヒットしないので0件のupdateで終了しま。updateす前の情報を見て勘違いしているだけではないでしょうか
49
49
 
50
50
  ```python
51
51
  db.c.execute('update twitter_users set comment = ? where name = ?', (comment, name))

2

追記

2019/10/29 05:11

投稿

quickquip
quickquip

スコア11314

answer CHANGED
@@ -36,4 +36,22 @@
36
36
  ```
37
37
 
38
38
  パッとやる限りは再現しないですね……。
39
- DBを中身をどうやって確認したかと、Pythonのバージョンを明記してもらえるといいかと思いました。
39
+ DBを中身をどうやって確認したかと、Pythonのバージョンを明記してもらえるといいかと思いました。
40
+
41
+ ----
42
+
43
+ 追記
44
+
45
+ ```python
46
+ db.c.execute('update twitter_users set comment = ? where name = ?', (name, comment))
47
+ ```
48
+ だとnameとcommentが逆です(からwhere句でヒットしないので0件のupdateで終了する)。
49
+
50
+ ```python
51
+ db.c.execute('update twitter_users set comment = ? where name = ?', (comment, name))
52
+ ```
53
+
54
+ ```python
55
+ db.c.execute('update twitter_users set comment = :comment where name = :name', {'name': name, 'comment': comment})
56
+ ```
57
+ にしましょう。

1

追記

2019/10/29 00:26

投稿

quickquip
quickquip

スコア11314

answer CHANGED
@@ -2,4 +2,38 @@
2
2
 
3
3
  [https://docs.python.org/ja/3.7/library/sqlite3.html](https://docs.python.org/ja/3.7/library/sqlite3.html)
4
4
  > たいてい、SQL 操作では Python 変数の値を使う必要があります。この時、クエリーを Python の文字列操作を使って構築することは安全とは言えないので、すべきではありません。そのようなことをするとプログラムが SQL インジェクション攻撃に対し脆弱になります (https://xkcd.com/327/ ではどうなってしまうかをユーモラスに描いています)。
5
- 代わりに、DB-API のパラメータ割り当てを使います。 ? を変数の値を使いたいところに埋めておきます。その上で、値のタプルをカーソルの execute() メソッドの第2引数として引き渡します。(他のデータベースモジュールでは変数の場所を示すのに %s や :1 などの異なった表記を用いることがあります。) 例を示します:
5
+ 代わりに、DB-API のパラメータ割り当てを使います。 ? を変数の値を使いたいところに埋めておきます。その上で、値のタプルをカーソルの execute() メソッドの第2引数として引き渡します。(他のデータベースモジュールでは変数の場所を示すのに %s や :1 などの異なった表記を用いることがあります。) 例を示します:
6
+
7
+ ----
8
+
9
+ コメントへ
10
+
11
+ ```python
12
+ import sqlite3
13
+
14
+ conn = sqlite3.connect('example.db')
15
+ c = conn.cursor()
16
+
17
+ # Create table
18
+ c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
19
+
20
+ c.execute("INSERT INTO stocks VALUES ('2006-01-05', ? ,'RHAT',100,35.14)", ("ho'ge",))
21
+
22
+ # Save (commit) the changes
23
+ conn.commit()
24
+
25
+ for row in c.execute('SELECT * FROM stocks ORDER BY price'):
26
+ print(row)
27
+
28
+ # We can also close the connection if we are done with it.
29
+ # Just be sure any changes have been committed or they will be lost.
30
+ conn.close()
31
+ ```
32
+
33
+ 結果
34
+ ```
35
+ ('2006-01-05', "ho'ge", 'RHAT', 100.0, 35.14)
36
+ ```
37
+
38
+ パッとやる限りは再現しないですね……。
39
+ DBを中身をどうやって確認したかと、Pythonのバージョンを明記してもらえるといいかと思いました。