使用pymysql.cursor()将元组值插入mysql表

时间:2018-07-18 11:02:31

标签: python mysql-python pymysql

第1步:首先,我已连接到数据库,并从mysql表中提取了2列中的所有行 (idnum,clientname) > 例如:(1234,renolds),(1235,renolds2)

Step2 :然后,每个idnum都有一个单独的表 例如:sample_divya_1234; sample_divya_1235, 从这些表中的每一个中,我们需要获取所有电子邮件和名称。
 (注意:每个idnum都有许多电子邮件和lname记录)

Step3 :步骤1中获取的所有客户端名称都存在于另一个表sample_divya3中,因此对于每个客户端名称都需要提取fname 例如:(saha,renolds)

第4步:现在,电子邮件,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      |
    +--------+------------+

请帮助我

4 个答案:

答案 0 :(得分:1)

尝试

 ConstraintLayout mViewA = (ConstraintLayout) findViewById(R.id.layoutViewA);
 //the view becomes sensitive to touch
 mViewA.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Toast.makeText(this, "Layout touched",Toast.LENGTH_LONG).show();
                return false;
            }
        });

数据应为字典

答案 1 :(得分:1)

尝试以下

for id, client in data:
    print "==========="
    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 df 
    print "------------"
    print data1
    print "~~~~~~~~~~~~~~~~~"
    data2= data1* len(df)

    print zip(df,data2)

    for x ,y in zip(df,data2):
        dat = """insert into sql_table1  values (%s,%s,%s)""", (x[0], x[1],y[0])
        print dat

    # dat = """insert into sql_table1  values (%s,%s,%s)""", (
    #     df[0][0], df[0][1], data1[0][0])
    # 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
conn.commit()
conn.close()

=========================================

输出:

===========

('插入sql_table1值(%s,%s,%s)',('divya@gmail.com','sai','hasini')) ('插入sql_table1值(%s,%s,%s)',('sainag@gmail.com','nagandla','hasini')) ('插入sql_table1值(%s,%s,%s)',('venu@gmail.com','venugopal','hasini'))

===========

('插入sql_table1值(%s,%s,%s)',('pavan@yahoo.com','inaganti','saha')) ('插入sql_table1值(%s,%s,%s)',('sahasra@gmail.com','sahasra','saha'))

===========

(''插入sql_table1值(%s,%s,%s)',('gopal@gmail.com','venugopal','chinn')) ('插入sql_table1值(%s,%s,%s)',('vishnu@gmail.com','vishnu','chinn'))

===========

说明:

在上面的代码中,zip(A,B)将元组的长度切成较小的元组对象的长度。所以我通过复制元组来匹配元组的长度。同样,请注意,此解决方案仅在表sample_divya3中所有client_num只有一个fname的情况下才有效。

示例:

>>> A=((1,2),(2,3))
>>> B=(('A',))
>>> zip(A,B)
[((1, 2), 'A')]

答案 2 :(得分:0)

终于知道了:

  for id,filename,name,client in data_1:
        sql="select '{}',email,lname from sample_divya_{}".format(name,id)
        cursor.execute(sql)
        data_2=cursor.fetchall()
        conn.commit()
        data=list(data_2)
        df=pd.DataFrame(data)

试图将所有内容放入一个查询中,以从两个表中提取数据。 对于元组插入,我首先将元组转换为列表,然后转换为datafram并将其放入csv

答案 3 :(得分:0)

您可以通过以下方式完成

cursor.execute("insert into sql_table1  values %s", (your_tuple,))
    

重要的是your_tuple应该是tuple()而不是list()