无法使用python的pymysql将csv文件导入sql服务器

时间:2019-06-06 08:04:06

标签: python mysql pymysql

我有一个非常简单的csv文件,其中包含3列,整数名称为“ a”,“ b”,“ c”,具有5列。我想将此数据导入具有pymysql的数据库中的SQL Server中。有人可以为此提供我的代码吗?还需要PHPMyAdmin吗?

这是我的实际代码:

import pymysql

f = open(r"a.csv", "r")
fString = f.read()
print(fString)
fList = []

for line in fString.split('\n'):
    fList.append(line.split(','))
    del(fList[0])
conn = pymysql.connect(host='localhost', user='root',
                           password='ajit2910@', database='mydatabase')
cur = conn.cursor()
cur.execute('CREATE TABLE jogi4(a INT,b INT,c INT)')
for i in range(len(fList)-1):
        sqlquery = "INSERT INTO jogi3(a,b,c) VALUES(%s,%s,%s)"
        cur.execute(sqlquery, (fList[i][0], fList[i][1], fList[i][2])) conn.close()

1 个答案:

答案 0 :(得分:0)

基本上,您的问题是创建表jogi4并将其插入jogi3中。我正在写更详细的答案。

这是带注释的更正代码。

基本上:

  • 改进:使用CSV模块避免解析
  • 修复:在任何地方都使用jogi4
  • 修复: COMMIT SQL事务。
import pymysql
import csv

# create the connection BEFORE to avoid recreating it at each loop
conn = pymysql.connect(host='localhost', user='root', database='stackoverflow')
cur = conn.cursor()
# Adds an 'IF NOT EXISTS' clause to avoid an Exception if the table already exists
cur.execute('CREATE TABLE IF NOT EXISTS jogi4(a INT,b INT,c INT)')

csvfile = open('a.csv')
# Use a CSV reader to avoid having to parse the CSV file myself
reader = csv.reader(csvfile)
# Skip the header
next(reader, None)

for row in reader:
    sqlquery = "INSERT INTO jogi4(a,b,c) VALUES(%s,%s,%s)"
    s = cur.execute(sqlquery, (row[0], row[1], row[2]))

cur.close()

# You forgot to commit the inserts, see "Transactions" in SQL
conn.commit()

conn.close()