![](/img/trans.png)
[英]insert into SQL Server table using python from CSV and Text file
[英]insert into mysql table using python from text file
import MySQLdb
db = MySQLdb.connect(host="?",
user="root",
passwd="?",
db="test")
cursor = db.cursor()
file = open('...../EM.txt', 'r')
file_content = file.read()
file.close()
query = "INSERT INTO EM VALUES (%s,%s,%s,%s,%s,%s)"
cursor.execute(query, (file_content,))
db.commit()
db.close()
我已經嘗試使用此代碼從文本文件中讀取並插入到 EM 表中……任何人都可以幫助我完成這項工作嗎?
您是要將整個文本文件插入數據庫中的字符串列,還是要將表格數據導入數據庫? 似乎您想根據指定值的方式導入表格數據,所以我將使用它作為我的假設。
為此,您需要從文件中讀取每一行並將其一次插入到數據庫中。 您還需要更新查詢語法以指定要插入的列名。
import csv
import MySQLdb
db = MySQLdb.connect(host='localhost',
user='root',
passwd='?',
db='test')
cursor = mydb.cursor()
with open('...../EM.txt') as f:
reader = csv.reader(f)
for row in reader:
cursor.execute("""INSERT INTO testcsv(col1, col2, col3, col4, col5, col6)
VALUES(%s, %s, %s, %s, %s, %s)
""", row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
我不知道您的文本文件是如何格式化的,但是file.read()
將整個文件作為單個字符串提供給您,並且您似乎有六個字段要填寫。 那么也許該文件由 6 個制表符或空格分隔的字段組成?
首先,使用file.readlines()
而不是file.read()
將文件分成幾行。 接下來,構建一個可以輸入executemany
的行列表:
values = [line.split() for line in file_content]
cursor.executemany(query, values)
split
方法將文件中的行拆分為一個元組,例如,字符串ab c
被轉換為元組('a', 'b', 'c')
,以便列表推導生成元組列表可以將其輸入cursor.executemany
以執行批量插入。
正如@Evan 指出的那樣,您還必須在 SQL 查詢中指定值關聯的列,例如,
INSERT INTO EM (field, spam, ham, eggs, price, ni) VALUES (%s, %s, %s, %s, %s, %s)
我認為你的問題是 readlines() 和 values = [line.split() for line in file_content]
要開始讓 python 與您的 SQl 數據庫通信,您必須使用一個適配器,例如 psycopg2。 安裝 psycopg2 后,您必須導入它。 另一個可以提高代碼的簡單性和功能性的部分是使用 csv 閱讀器。 這可以通過簡單地導入 csv 來完成。SQL 數據庫存儲為 csv 文件,因此使用它可以幫助您在使用 python 時讀取 csv 文件。
您可以在此處找到有關使用 csv 閱讀器的更多信息: https://docs.python.org/2/library/csv.html
根據您的代碼試試這個:
import MySQLdb
import psycopg2
db = MySQLdb.connect(host="?",
user="root",
passwd="?",
db="test")
cursor = db.cursor()
file = open('...../EM.txt', 'r')
file_content = file.read()
file.close()
query = "INSERT INTO EM VALUES (%s,%s,%s,%s,%s,%s)"
cursor.execute(query, (file_content,))
db.commit()
db.close()
通過安裝和導入 psycopg2 將允許 python 理解您嘗試執行的 SQL 請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.