[問題] SQLite insert 問題

作者: alansyue (alansyue)   2018-06-23 14:36:15
大家好,小弟是 Python 新手,非本科系自學
最近在學習將 Python 的資料匯入 SQLite
我先建一個SQLite的資料表
import sqlite3
conn = sqlite3.connect('sqlite01.db')
print("Opened database successfully")
c = conn.cursor()
c.execute('''CREATE TABLE worknowapp_job
(ID INT PRIMARY KEY NOT NULL,
JOB_NAME CHAR NOT NULL,
JOB_URL CHAR NOT NULL);''')
print("Table created successfully")
conn.commit()
conn.close()
接著我想試將設定好的變數寫入 SQLite,程式碼如下:
import sqlite3
name ="測試1"
url = "/jobs/10101"
conn = sqlite3.connect('sqlite01.db')
c = conn.cursor()
print ("Opened database successfully")
c.execute("INSERT INTO worknowapp_job (ID,JOB_NAME,JOB_URL) \
VALUES (1,name,url )");
conn.commit()
print("Records created successfully")
conn.close()
但卻出現以下的錯誤訊息:
作者: s8300355 (s8300355)   2018-06-23 15:38:00
c.execute("INSERT INTO worknowapp_job (ID,JOB_NAME,J執行的地方改成這樣應該可以VALUES (%d,'%s','%s')" % (1, name, url)或者這樣 VALUES (?, ?, ?)" , (2, name, url)
作者: MAGICXX (逢甲阿法)   2018-06-23 16:15:00
推薦用%s ?很容易爆炸
作者: alansyue (alansyue)   2018-06-24 01:20:00
成功了,謝謝樓上兩位大大

Links booklink

Contact Us: admin [ a t ] ucptt.com