这段代码是把Excel数据导入到MySQL中,后续会比较Excel数据正确性,并将错误数据导出到Excel。
import xlrd, MySQLdb
def db_connect():
conn = MySQLdb.connect("localhost", "root", "root", "test")
return conn
def open_excel(filename):
excel = xlrd.open_workbook(filename)
return excel
def read_excel():
sheet = open_excel('users.xlsx').sheet_by_index(0)
nrows = sheet.nrows
conn = db_connect()
conn.set_character_set("utf8")
cursor = conn.cursor()
try:
for i in range(0, nrows):
name = sheet.cell_value(i, 0)
num = sheet.cell_value(i, 1)
cursor.execute("insert into users(name, num) values (%s, %s)", (name, num))
except Exception, e:
print e
conn.rollback()
conn.commit()
conn.close()
def main():
read_excel()
if __name__ == '__main__':
main()
下面是比较用户数据:
import MySQLdb
def conn_location():
conn = MySQLdb.connect("localhost", "root", "root", "test")
return conn
def conn_remote():
conn = MySQLdb.connect("localhost", "intime4", "root", "intime4")
return conn
def locationData():
conn = conn_location()
conn.set_character_set("utf8")
cursor = conn.cursor()
cursor.execute("select * from users")
results = cursor.fetchall()
conn.close()
return results
def remoteData(id):
conn = conn_remote()
conn.set_character_set("utf8")
cursor = conn.cursor()
sql = "select id, cust_name, credentials_number from od_order_info where credentials_number = '%s'" % id
cursor.execute(sql)
results = cursor.fetchall()
conn.close()
return results
def checkRemoteData():
lResults = locationData()
for l in lResults:
name = l[1]
id = l[2].strip()
rResults = remoteData(id)
if len(rResults) == 0:
print id, name
for r in rResults:
if name != r[1]:
print r[0], r[1], r[2]
def main():
checkRemoteData()
if __name__ == '__main__':
main()
由于不一致的数据量很少,就没有导出到Excel。
但过程中遇到个问题,从数据库中读取数据时在第一个for循环中有一条数据不知道为什么前面出现了空格,最后使用l[2].strip()解决了,如果有知道答案的请回复我,谢谢!