简体   繁体   English

如何使用python_列将csv文件插入数据库

[英]How to Insert csv files to database using python_ columns

This is my code 这是我的代码

import pymysql
import csv

conn=pymysql.connect("localhost", "root","****","finance")
cursor=conn.cursor()       

print "done"
csv_data = csv.reader(file('naver_loan_output.csv'))

for row in csv_data:
    cursor.execute('INSERT INTO 'daily_new' (date,cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond )' 'VALUES("%s", "%s", "%s", "%s", "%s", "%s")',row)
    conn.commit()
    cursor.close()
    print "Done"

And this is the error: 这是错误:

File "D:\\dropbox\\Dropbox\\lab\\7_0218\\insert_daily_new.py", line 13 cursor.execute('INSERT INTO 'daily_new' (date,cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond )' 'VALUES("%s", "%s", "%s", "%s", "%s", "%s")',row) ^ SyntaxError: invalid syntax [Finished in 0.104s] 文件“ D:\\ dropbox \\ Dropbox \\ lab \\ 7_0218 \\ insert_daily_new.py”,第13行cursor.execute('INSERT INTO'daily_new'(date,cust_bal,cust_credit,fund_stock,fund_hyb,fund_bond)''VALUES(“%s “,”%s“,”%s“,”%s“,”%s“,”%s“)',行)^ SyntaxError:无效的语法[在0.104s中完成]

I tried a lot, but I'm not sure about the proper SQL insert query syntax. 我做了很多尝试,但是我不确定正确的SQL插入查询语法。 How do I get columns from csv? 如何从csv获取列? There are 6 columns in my csv file. 我的csv文件中有6列。

With this updated example, code works: 通过此更新的示例,代码可以工作:

import pymysql
import csv

csv_data= csv.reader(file('naver_loan_output.csv'))

conn=pymysql.connect("localhost","finance")
cursor=conn.cursor()
print "Done"
for row in csv_data:
    #cursor.execute('INSERT INTO \'daily_new\' (date, cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond ) VALUES({}, {}, {}, {}, {}, {})'.format(row[0], row[1], row[2], row[3], row[4], row[5]))
    sql="INSERT INTO  daily_n (date,cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond ) VALUES('2017-01-01','2','2','2','2','2')"
    cursor.execute(sql)
    conn.commit()

cursor.close()

So, I think the for row or %s is the problem. 因此,我认为for row%s就是问题。

Mainly, your quotes is the issue. 主要是您的报价是问题。

  1. You need to escape single quotes if larger sql string is wrapped in single quotes; 如果较大的sql字符串用单引号引起来,则需要转义单引号。 or simply wrap larger string in double quotes like your updated example. 或者只是将较大的字符串用双引号引起来,例如更新后的示例。 And note: the SyntaxError is a Python compile error (not MySQL runtime exception). 请注意: SyntaxError是Python编译错误(不是MySQL运行时异常)。
  2. For parameterized queries, do not quote the placeholder, %s . 对于参数化查询,请勿引用占位符%s
  3. MySQL (and practically for all RDMS's) do not use single quotes to enclose table and column name references as you do with 'daily_new' . MySQL(实际上对于所有RDMS而言)都不像'daily_new'那样使用单引号将表和列名称引用括起来。 Use backticks for names in MySQL. 在MySQL中使用反引号作为名称。 A few databases and the ANSI standard allows the double quote for object identifiers (not string literals). 一些数据库和ANSI标准允许对象标识符(而不是字符串文字)使用双引号。

Consider the following adjustment with a more efficient read process of csv file using with() as opposed to all at once as you have it with file() . 通过考虑以下调整与csv文件的更有效的读取过程with()而不是一次全部为你拥有它file() And as shown with parameterization, you can prepare the sql statement once and then just bind values iteratively in loop. 如参数化所示,您可以准备一次sql语句,然后只需迭代地绑定值即可。

strSQL = "INSERT INTO `daily_new` (`date`, cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond )" + \
         " VALUES(%s, %s, %s, %s, %s, %s)"

with open('naver_loan_output.csv', 'r') as f:
    csv_data = csv.reader(f)
    for row in csv_data:
        cursor.execute(strSQL, row)
        conn.commit()

cursor.close()
conn.close()

print "Done"

I think that you can try something like this: 我认为您可以尝试执行以下操作:

query = """'INSERT INTO 'daily_new' (date,cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond )' 'VALUES("""+row+""")'"""
cursor.execute(query)

Just see this code fragment from CSV File Reading and Writing doc : 只需从CSV文件读写文档中看到以下代码片段即可:

>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

I hope it is useful to you or that puts you in the way. 我希望它对您有用,否则会给您带来麻烦。

There are three problems tripping you up: 有三个问题使您绊倒:

  1. String escape characters 字符串转义字符

In your code is that the single quote before daily_new is stopping the string and python is interpreting daily_new as a variable, which is not defined. 在您的代码中, daily_new之前的单引号会终止字符串,而python会将daily_new解释为未定义的变量。

To solve this you should use the escape character "\\" directly before each single quote you want in the string like this: 为了解决这个问题,您应该字符串中想要的每个单引号之前直接使用转义字符“ \\”:

cursor.execute('INSERT INTO \'daily_new\' (date,cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond ) VALUES("%s", "%s", "%s", "%s", "%s", "%s")',row)
  1. Column access 列访问

The csv module returns rows as a list. csv模块将行作为列表返回。 To access an element in a list (or row in your case), use bracket notation. 要访问列表(或您的情况下的行)中的元素,请使用方括号表示法。 For row[0] accesses the first element (column) in a row, and row[5] accesses the 6th column. 对于row[0]访问row[0]的第一个元素(列),而row[5]访问第6列。

  1. String substitution 字符串替换

The third problem you are facing is how to pass the values into the string substitution correctly. 您面临的第三个问题是如何将值正确传递到字符串替换中。 While there are many ways to do this, an easy one is the format() method. 尽管有很多方法可以做到这一点,但一种简单的方法就是format()方法。 For example: if I wanted to build a string that says "Count is 1", I could run "Count is {}".format(1) . 例如:如果我想构建一个字符串“ Count is 1”,则可以运行"Count is {}".format(1)

In your case you want to add 6 values to the string, so you add a pair of {} wherever you want a value substituted into a string and add another parameter to the format() function. 在您的情况下,您想在字符串中添加6个值,因此无论您想将值替换为字符串中的任意位置,都添加一对{}并在format()函数中添加另一个参数。

Putting it all together 放在一起

So, to correct your loop code you would want something like this: 因此,要更正循环代码,您需要以下代码:

csv_data = csv.reader(file('naver_loan_output.csv'))
for row in csv_data:
    cursor.execute('INSERT INTO daily_new (date, cust_bal, cust_credit, fund_stock, fund_hyb, fund_bond ) VALUES ({}, {}, {}, {}, {}, {})'.format(row[0], row[1], row[2], row[3], row[4], row[5]))

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

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