Python 如何循环这个对象并将每一行插入mysql数据库表

Python 如何循环这个对象并将每一行插入mysql数据库表,python,mysql,csv,gnupg,Python,Mysql,Csv,Gnupg,我的问题如下: [root@localhost dest]# python Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> im

我的问题如下:

[root@localhost dest]# python 
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.


>>> import csv
>>> import MySQLdb
>>> import gnupg

>>> gpg = gnupg.GPG(gnupghome="/home/chefgit/Desktop/.gnupg")
>>> file = open("/home/chefgit/Desktop/csv/dest/file_100.gpg", 'r+')
>>> decrypt = gpg.decrypt_file(file)

>>> import StringIO
>>> csv_input = csv.reader(StringIO.StringIO(decrypt))

>>> import MySQLdb
>>> connect = MySQLdb.connect\
('localhost', 'chefgit', 'password', 'python_db_1')

>>> cursor = connect.cursor()
>>> cursor.execute("SELECT VERSION()")

   1L

>>> print (cursor.fetchone())

    ('5.1.73',)

>>> sql = "INSERT INTO python_db_1

('id', 'first_name', 'last_name', 'email', 'country', 'ip_address')VALUES\ 
('%d', '%s', '%s', '%s', '%s', '%s')"

>>> csv_input = csv.reader(StringIO.StringIO(decrypt)
>>> for row in csv_input:
...        if csv_input.line_num == 1:
...              continue
...        cursor.execute(sql '%row')

     File "<stdin>", line 4
     cursor.execute(sql '%row')
                        ^
     SyntaxError: invalid syntax
>>> 
我很难弄清楚如何遍历这些行并将它们加载到MySQL数据库表中


我必须循环通过从StringIO.StringIOdecrypt获取的csv_输入变量,逐行读取数据,并将数据加载到数据库表中。我无法从文件中读取它。我必须从记忆中的物体中读出它。这是老板对我的要求

您是否尝试过使用.executemany函数?我真的不明白你认为你在用cursor.executesql“%row”做什么。您正在传递两个单独的参数,以执行它们之间的空格。您正在尝试格式化sql字符串吗?或者您正在尝试用sql字符串连接任何“行”吗?感谢您的响应。我去吃午饭,刚回来。我对python完全陌生。我开始这项工作,第一天他们就让我用python编写脚本。他们不在乎我不知道,他们说去查一下。所以我只是尽我最大的努力。我将尝试ExecuteMy并返回结果。再次感谢您的响应。我正在尝试将任何行连接到sql字符串。由于您将csv_输入设置为读取字符串,因此您的变量行已经是所需的字符串。因此,只需使用cursor.executesql+row即可将它们连接起来