使用python导出特定值的mysql数据

时间:2015-12-16 15:54:16

标签: python mysql

我试图从mysql数据库table1获取特定的数据行。我正在查看其中一个列中显示某个ID的位置。

我在查询'下的SELECT WHERE语句中遇到了我的代码问题。当我要求特定的id(id_2_lookup)时,我会导出整个表。我哪里错了?

# Establish a MySQL connection
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()

#to export to excel
import xlsxwriter
from xlsxwriter.workbook import Workbook

#to get the datetime functions
import datetime
from datetime import datetime


#creates the workbook
workbook = xlsxwriter.Workbook('imheretoo.xlsx')
worksheet = workbook.add_worksheet()

#formatting definitions
bold    = workbook.add_format({'bold': True})
date_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
timeShape =  '%Y-%m-%d %H:%M:%S'


query = ("SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 ")
"WHERE id1_active  '%s'"
id_2_lookup = [input('Who are you looking for:'),0]




# Execute sql Query
cursor.execute(query)
result = cursor.fetchall()


#sets up the header row
worksheet.write('A1','sent_time',bold)
worksheet.write('B1', 'delivered_time',bold)
worksheet.write('C1', 'customer_name',bold)
worksheet.write('D1', 'id1_active',bold)
worksheet.write('E1', 'id2_active',bold)
worksheet.write('F1', 'id3_active',bold)
worksheet.write('G1', 'id1_inactive',bold)
worksheet.write('H1', 'id2_inactive',bold)
worksheet.write('I1', 'id3_inactive',bold)
worksheet.write('J1', 'location_active',bold)
worksheet.write('K1', 'location_inactive',bold)
worksheet.autofilter('A1:K1')



print("sent_time", "delivered_time", "customer_name", "id1_active", "id2_active", "id3_active", "id1_inactive", "id2_inactive", "id3_inactive", "location_active", "location_inactive")
for row in result:
    print(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10])

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(result, start=1):  #where you want to start printing results inside workbook
    for c, col in enumerate(row):
        worksheet.write_datetime(r,0,row[0], date_format)
        worksheet.write_datetime(r,1, row[1], date_format)
        worksheet.write(r,2, row[2])
        worksheet.write(r,3, row[3])
        worksheet.write(r,4, row[4])
        worksheet.write(r,5, row[5])
        worksheet.write(r,6, row[6])
        worksheet.write(r,7, row[7])
        worksheet.write(r,8, row[8])
        worksheet.write(r,9, row[9])
        worksheet.write(r,10, row[10])




#close out everything and save
cursor.close()
workbook.close()
conn.close()

#print number of rows and bye-bye message
print ("- - - - - - - - - - - - -")
rows = len(result)
print ("I just imported "+ str(rows) + " rows from MySQL!")
print ("")
print ("Good to Go!!!")
print ("")

我想向您提供我所有其他文件的所有信息以及我拍摄的内容,看看您是否可以复制并实际让它工作,看看它是不是只是我的系统或我有一些配置..

我有一个带有一个table的数据库。我们称之为'table1'该表按照以下列分类:

sent_time | deliver_time | id1_active | id2_active | id3_active | id1_inactive | id2_inactive | id3_inactive | location_active | location_inactive ... ..`更多

让我们说这些是两个或更多的客户互相送货。每个客户都有三个id#s。

我创建了一个'config.ini'文件,让我的生活更轻松

[mysql]
host = localhost
database = db_name
user = root
password = blahblah

我创建了'python_mysql_dbconfig.py'

from configparser import ConfigParser

def read_db_config(filename=’config.ini’, section=’mysql’):
“”” Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
“””
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)

# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception(‘{0} not found in the {1} file’.format(section, filename))

return db

我现在有了我们一直在努力的代码,但现在已经更新了我们所做的更改,但仍然出现错误......

# Establish a MySQL connection
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()

#to export to excel
import xlsxwriter
from xlsxwriter.workbook import Workbook

#to get the datetime functions
import datetime
from datetime import datetime


#creates the workbook
workbook = xlsxwriter.Workbook('imheretoo.xlsx')
worksheet = workbook.add_worksheet()

#formatting definitions
bold    = workbook.add_format({'bold': True})
date_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
timeShape =  '%Y-%m-%d %H:%M:%S'

#actual query

id_2_lookup= [input('Who are you looking for:'),0]

query = (
    """SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 "
    "WHERE id1_active = %s""",(id_2_lookup)
)

# Execute sql Query

query = query % id_2_lookup
cursor.execute(query)
result = cursor.fetchall()



#sets up the header row
worksheet.write('A1','sent_time',bold)
worksheet.write('B1', 'delivered_time',bold)
worksheet.write('C1', 'customer_name',bold)
worksheet.write('D1', 'id1_active',bold)
worksheet.write('E1', 'id2_active',bold)
worksheet.write('F1', 'id3_active',bold)
worksheet.write('G1', 'id1_inactive',bold)
worksheet.write('H1', 'id2_inactive',bold)
worksheet.write('I1', 'id3_inactive',bold)
worksheet.write('J1', 'location_active',bold)
worksheet.write('K1', 'location_inactive',bold)
worksheet.autofilter('A1:K1')



print("sent_time", "delivered_time", "customer_name", "id1_active", "id2_active", "id3_active", "id1_inactive", "id2_inactive", "id3_inactive", "location_active", "location_inactive")
for row in result:
    print(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10])

# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(result, start=1):  #where you want to start printing results inside workbook
    for c, col in enumerate(row):
        worksheet.write_datetime(r,0,row[0], date_format)
        worksheet.write_datetime(r,1, row[1], date_format)
        worksheet.write(r,2, row[2])
        worksheet.write(r,3, row[3])
        worksheet.write(r,4, row[4])
        worksheet.write(r,5, row[5])
        worksheet.write(r,6, row[6])
        worksheet.write(r,7, row[7])
        worksheet.write(r,8, row[8])
        worksheet.write(r,9, row[9])
        worksheet.write(r,10, row[10])




#close out everything and save
cursor.close()
workbook.close()
conn.close()

#print number of rows and bye-bye message
print ("- - - - - - - - - - - - -")
rows = len(result)
print ("I just imported "+ str(rows) + " rows from MySQL!")
print ("")
print ("Good to Go!!!")
print ("")

1 个答案:

答案 0 :(得分:2)

在您最初发布的代码中,where子句实际上并未作为查询的一部分包含在内。我最初没有注意到的是,您将input来电的结果包含在您尝试提供给cursor.execute来电的列表中。由于您的查询字符串中只有一个要替换的标记,因此无法正常工作。如果我们假设用户输入id1_active的值,那么我认为您需要以下内容:

query = (
    "SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 "
    "WHERE id1_active = %s"
)
id_2_lookup = input('Who are you looking for:')
# Execute sql Query
cursor.execute(query, (id_2_lookup, ))

这会尝试将用户输入的数据与id1_active进行匹配。显然,如果这不符合您的意图,您必须根据需要调整查询。

原则上,您可以自己插入输入值,而不是依靠cursor.execute为您执行此操作。在那种情况下,

query = (
    "SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 "
    "WHERE id1_active = %s"
)
id_2_lookup = input('Who are you looking for:')
# Execute sql Query
query = query % id_2_lookup
cursor.execute(query)

这会将值直接插入查询中,以便cursor.execute只查看查询字符串,并且不需要进行任何替换。一般来说,你的方式更好。