简体   繁体   English

使用Mac将Python导入CSV到SQL

[英]Importing a csv into sql using python using mac

I cant seem to get this code to work. 我似乎无法使此代码正常工作。 It is a relatively small csv file. 这是一个相对较小的csv文件。 The terminal responds with an error stating there is an issue with the sql syntax. 终端以一条错误响应,指出sql语法存在问题。 I think one issue may be macs default use of numbers. 我认为一个问题可能是Mac默认使用数字。 I would just like to load this file into sql with two columns and all of the respective data. 我只想将此文件加载到具有两列和所有相应数据的sql中。 The database and table has already been created in SQL. 数据库和表已经在SQL中创建。

import pymysql 
import csv
import time

with open('code1.csv') as file:
    reader = csv.reader(file, delimiter=',')
    conn = pymysql.connect(host='', port=, user='', passwd='', db='', autocommit=True) 
    cur = conn.cursor(pymysql.cursors.DictCursor)

    line = 0
    for row in reader:
        if line == 0:
            line +=1
        else:
            sql = "INSERT INTO name_project('Code', 'Definition')VALUES(%s,%s);"
            cur.execute(sql, (row[0], (str(row[1]))))
cur.close()
conn.close()

If you want to do it this way, there are 1 or 2 syntax errors: 如果要用这种方法,则存在1或2个语法错误:

  1. Missing a empty space before 'VALUES' “ VALUES”前缺少空白
  2. Unless your are using dialect such as Postgres, 'Code', 'Definition' may ought to be [Code], [Definition] or just plain Code, Definition` 除非您使用诸如Postgres之类的方言,否则'Code', 'Definition' may ought to be [代码],[定义] or just plain代码,定义'Code', 'Definition' may ought to be

Additionally, you may want to consider using pandas to read the whole csv file as a DataFrame using .read_csv , then write to your db with .to_sql . 此外,你可能要考虑使用pandas读取整个CSV文件作为一个DataFrame使用.read_csv ,然后写你的分贝.to_sql

First off, general advice in such situations is to check what the query that you're passing is, ie print the query, check whether it's syntax matches an sql query(you'd be surprised how much we overlook things). 首先,在这种情况下的一般建议是检查您要传递的查询是什么,即打印查询,检查其语法是否与sql查询匹配(您会惊讶于我们忽略了多少东西)。

Next run this sql query in the relevant sql server, this might also help in filtering your errors. 接下来,在相关的sql服务器中运行此sql查询,这也可能有助于过滤错误。 Later look for syntactical errors. 稍后查找语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM