前提・実現したいこと
pythonでSQLiteを使ってデータベースに接続し値を格納したい。
text型の変数your_nameを用いてデータベースに値を格納したい。
発生している問題・エラーメッセージ
text型の値の格納を試みた結果エラーが出ているが意味が分からない。
以下がエラー文です。
3度実行しています。
1番目がtext型の値格納(エラー)
ここで一度データベースを削除
2番目がint型の値格納(正常動作)
3番目がint型の値格納2回目(エラー)←投稿後解決、pyファイルではなくdbファイルを実行していた。
(base) C:\Users\Anonymous>cd web (base) C:\Users\Anonymous\web>cd cgi-bin (base) C:\Users\Anonymous\web\cgi-bin>python Debug.py Traceback (most recent call last): File "Debug.py", line 33, in <module> cur.execute("insert into studentTable(your_name)values({0});".format(input_your_name)) sqlite3.OperationalError: near "name": syntax error (base) C:\Users\Anonymous\web\cgi-bin>python Debug.py 5678 (base) C:\Users\Anonymous\web\cgi-bin>python Debug.db File "Debug.db", line 1 SQLite format 3 ^ SyntaxError: invalid syntax (base) C:\Users\Anonymous\web\cgi-bin>
該当のソースコード
python
1 2#! /usr/bin/env python3 3 4import sqlite3 5import csv 6import sys 7import io 8 9# windowsにおける文字化け回避 10sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") 11 12# 使用するデータベースを指定 13db_path = "Debug.db" 14 15# student.dbを使ってsqlite3を起動 16con = sqlite3.connect(db_path) 17 18# 属性名で値を取り出すように設定 19con.row_factory = sqlite3.Row 20 21# カーソル(sqlでデータベースを操作するやつ)を作成 22cur = con.cursor() 23 24htmlText = "" 25 26input_your_name = "your name" 27#input_your_name = 5678#Debug 28# 以下sqlの実行 29 30cur.execute( 31 "create table studentTable(your_name text);"#←your_nameの型をintに変えてみたら正常動作 32) 33 34cur.execute("insert into studentTable(your_name)values({0});".format(input_your_name)) 35 36cur.execute("select * from studentTable;") 37rows = cur.fetchall() 38 39# データベースから値を取り出す 40if not rows: 41 htmlText = "No Data" 42else: 43 for row in rows: 44 if str(row["your_name"]): 45 htmlText += str(row["your_name"]) 46 47# データベースとの接続を保存・終了 48con.commit() 49con.close() 50 51print(htmlText)
試したこと
text型ではなくint型なら正常に動作した。
ただ2回目を実行すると失敗した。←解決
補足情報(FW/ツールのバージョンなど)
python 3.7.3
anaconda prompt
windows10
回答1件
あなたの回答
tips
プレビュー