【发布时间】:2018-12-26 06:37:44
【问题描述】:
第 1 步:首先我连接到一个数据库并从一个 mysql 表中拉出 2 列中的所有行 (idnum,clientname) 例如:(1234,renolds),(1235,renolds2)
Step2:然后每个idnum有一个单独的表
例如:sample_divya_1234;sample_divya_1235,
我们需要从每个表中获取所有电子邮件和 lname。
(注意:每个 idnum 都有许多电子邮件和 lname 记录)
Step3:在step1中获取的所有clientnames都存在于另一个表sample_divya3中,因此对于每个clientname都需要提取fname 例如:(saha , renolds)
第 4 步:现在必须将 email、lname、fname 都放入新表 sql_table1 中
进程:
import pandas as pd
import pymysql
import pymysql.cursors
from sqlalchemy import create_engine
from time import time
import datetime
conn=pymysql.connect(host= ,user='',password='',db='')
query = "select idnum,clientname from sample_divya1 where date(created_date)=date(now())"
cursor=conn.cursor()
cursor.execute(query)
data = cursor.fetchall()
cursor.execute("drop table if exists sql_table1")
sql_table = "create table sql_table1(email varchar(128),lname varchar(128),fname varchar(128))"
cursor.execute(sql_table)
for id,client in data:
data = " select email,lname from sample_divya_"+id
cursor.execute(data)
conn.commit()
df = cursor.fetchall()
print df
list_id="select fname from sample_divya3 where clientname='{}'".format(client)
cursor.execute(list_id)
conn.commit()
data1 = cursor.fetchall()
print data1
print type(data1)
for x,y in zip(df,data1):
cursor.execute("""insert into sql_table1 values (%s,%s,%s)""", (df[0][0], df[0][1],data1[0][0]))
conn.commit()
dat_1 = cursor.fetchall()
print dat_1
conn.commit()
conn.close()
获取输出:
+-----------------+----------+--------+
| email | lname | fname |
+-----------------+----------+--------+
| abc@yahoo.com | abcd | saha |
| xyz@gmail.com | xyza | hasini |
+-----------------+----------+--------+
但需要输出:
+------------------+----------+--------+
| email | lname | fname |
+------------------+----------+--------+
| abc@yahoo.com | abcd | saha |
| bcd@gmail.com | bcda | saha |
| xyz@gmail.com | xyza | hasini |
| nag@gmail.com | sai | hasini |
| hij@gmail.com | klm | hasini |
+------------------+----------+--------+
输入表: Sample_divya1:
+-------+------------+---
| idnum | clientname |
+-------+------------+-
| 1234 | renold |
| 1235 | renold1 |
+-------+------------+
sample_divya_1234
+-------------------+----------+
| email | lname |
+-------------------+----------+
| abc@yahoo.com | abcd |
| bcd@gmail.com | bcda |
+-------------------+----------+
**sample_divya_1235**
+------------------+-----------+
| email | lname |
+------------------+-----------+
| xyz@gmail.com | xyza |
| nag@gmail.com | sai |
| hij@gmail.com | klm |
+------------------+-----------+
**sample_divya3**
+--------+------------+
| fname | clientname |
+--------+------------+
| saha | renold |
| hasini | renold1 |
+--------+------------+
请帮帮我
【问题讨论】:
标签: python mysql-python pymysql