python pandas automatically generated test data into the database bulk mysql

1, python connected database cursors

# Coding: UTF-. 8 

from SQLAlchemy Import create_engine 

class connet_databases:
     DEF  the __init__ (Self):
         '' ' 
        # initialize the database connection, using pymysql module 
        # MySQL user: the root, password: 147369, Port: 3306, Database: mydb 
        ' ' ' 
        
        _host = ' 39.108.131.88 ' 
        _Port = 3306 
        _databases = ' san_jin_sq '   # ' Produce '# 

        _username = ' wuzaipei ' 
        _password = 'wuzaipei'

        self._connect = r'mysql+pymysql://{username}:{password}@{host}:{port}/{databases}'.format(
            username=_username,
            password=_password,
            host=_host,
            port=_port,
            databases=_databases)

engine = create_engine(connet_databases()._connect, echo=True)

2, the type of random string generated automatically

# Coding: UTF. 8- 
Import Random 

# randomly generated string of n listing 
DEF randomGenerateList (Al, n = 0):
     '' ' 
    : Al param: string list [' Journey ',' Monkey ',' lens' 'master'] 
    : n-param: n-generated list of strings of length 
    : return: 
    '' ' 
    alist = list (Al)
     return [the random.choice (alist) for _ in Range (n-)] 



DEF dict_conversion (COL, dict_list ):
     '' ' 
    : param COL: database field 
    : param dict_list: a list of all the fields which add dict 
    : return: merge into a table 
    ' ''
    col_ = list(col)
    dict_list_ = list(dict_list)
    return dict(zip(col_,dict_list_))

3, a small case

Import Random
 Import UUID
 from updateMsql.connectDatabases Import Engine
 from   updateMsql.generateDemand Import randomGenerateList, dict_conversion
 Import PANDAS AS PD 
COL = [ ' ID ' , ' date ' , ' species ' , ' batch ' , ' sales ' , ' sales amount ' ] 
DATE = pd.date_range ( ' 2018-7-11 ' , '2019-10-30 ' , FREQ = ' 1D ' ) 
n_index = DATE. The __len__ () 
ID = [_ for _ in Range (n_index)] 
field1 = randomGenerateList ([ ' three gold pieces ' , ' watermelon frost throat tablet ' , ' Guilin watermelon frost (spray) ' , ' watermelon frost lozenges qingyan ' ], n_index) 
Field2 = randomGenerateList ([ ' 1001 ' , ' 1002 ' , ' 1003 ' ,'1004','1005','1006'],n_index)
field3 = [random.randint(100,500) for i in range(n_index)]
field4 = [random.randint(500,1000) for j in range(n_index)]

data = pd.DataFrame(data=dict_conversion(col,[ID,date,field1,field2,field3,field4]))

data.to_sql('销售情况分析',engine,if_exists='replace',index=False)
print(data.head())
print("---- ----- successful insertion " )

4, the test results

 

Guess you like

Origin www.cnblogs.com/wuzaipei/p/11291428.html