Python 2.7 MySQLdb将从数据库读取的最后一行保存到文本文件中

时间:2016-09-12 17:15:39

标签: python mysql excel python-2.7

我的任务是获取MySQL数据库以将数据发送到Salesforce并创建票证。我目前有python从数据库下载所需的表并将该信息保存到.xlsx表。然后我有另一个python脚本将数据上传到Google Doc表,然后是一个Javascript触发器,它将数据提交到salesforce,并且所有工作都按照我的预期运行。

我遇到的问题是,当它从MySQL中提取数据时,它会一次又一次地提取相同的信息,我需要它记住它上次抓取的最后一行或客户ID,保存该ID或行到.txt文件然后在下次脚本运行时拉出相同的数据,因此它从该行或ID开始,而不是从顶部再次开始。

非常感谢任何帮助。

#!/usr/bin/python
import smtplib
import base64
import os
import sys
import csv
from xlsxwriter.workbook import Workbook
import xlwt
import MySQLdb
def sql_run():
ur = 'user' # your username
pd = 'password' # your password
ht = '192.168.1.10' # your host
pt = 3306
db = 'database' # database where your table is stored
#table = 'rma_customer' # table you want to save

con = MySQLdb.connect(user=ur, passwd=pd, host=ht, port=pt, db=db)
cursor = con.cursor()

query = "SELECT cus_id, cus_username FROM database.rma_customer"
query0 = "SELECT cus_firstname, cus_lastname, cus_cell_phone FROM database.rma_customer_details"
query1 = "SELECT cus_address_1 FROM database.rma_customer_address"
query2 = "SELECT cus_city, cus_postcode FROM database.rma_customer_address"
query3 = "SELECT regpro_model_type, regpro_buy_location, regpro_sn FROM database.rma_reg_product"
cursor.execute(query)
workbook = Workbook('outfile.xlsx')
sheet = workbook.add_worksheet("Warranty Info")
headers = ['ID', 'Email', 'FirstName', 'LastName', 'Phone', 'Street', 'City', 'Postal', 'Product', 'Store', 'SN']
for i, header in enumerate(headers):
    sheet.write(0, i, header)
for r, row in enumerate(cursor.fetchall()):
    r = r + 1
    for c, col in enumerate(row):

        sheet.write(r, c, col)

cursor.execute(query0)  
for r, row in enumerate(cursor.fetchall()):
    r = r + 1
    for c, col in enumerate(row):

        sheet.write(r, c+2, col)        

cursor.execute(query1)  
for r, row in enumerate(cursor.fetchall()):
    r = r + 1
    for c, col in enumerate(row):

        sheet.write(r, c+5, col)

cursor.execute(query2)  
for r, row in enumerate(cursor.fetchall()):
    r = r + 1
    for c, col in enumerate(row):

        sheet.write(r, c+6, col)

cursor.execute(query3)  
for r, row in enumerate(cursor.fetchall()):
    r = r + 1
    for c, col in enumerate(row):

        sheet.write(r, c+8, col)

cursor.close ()
workbook.close()
con.close ()
sys.exit()
# exit the program



sql_run()

1 个答案:

答案 0 :(得分:0)

  1. 在您提取信息的row中添加table
  2. id(第0行)作为唯一标识符
  3. 使用rowidTrue更新False
  4. 为您的查询提供condition,该行必须为True / False
  5. 这样你就可以确保它停止迭代相同的信息。

    编程方式:

    query = "SELECT cus_id, cus_username FROM database.rma_customer WHERE row = 'True'"
    ...
    
    data = cursor.execute(query)
    for col in data:
        id = col[0]
    ...
    cursor.execute("""
        UPDATE table
        SET row= %s
        WHERE id= %s
    """, (row, id))
    

    ...代表您的代码。我猜不出你想放置代码片段的位置。