以下是如何連接,製作表格和插入表格。
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
以上示例將一個表2周的cols,一個ID和一個名字
看here關於如何從字典中鍵和列表中插入的東西,值到SQL爲例,基本上你需要佔位
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()database
,或者你可以去this,例如一個簡單直接的字典
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())
我建議你使用JSON格式將它插入到MySQL中使用[this](https://docs.python.org/3/library/json.html) – Carlos
似乎沒有工作,因爲我得到這樣一個錯誤: 「TypeError:不是所有在字符串格式化過程中轉換的參數」 – sammtt
你能發佈你有問題的代碼塊嗎? – BlooB