Python randomly generates a specified length string and saves it in MySQL

Source: Internet
Author: User

See a python exercise online to randomly generate 8-digit coupons, and want to be saved to the MySQL database. I checked the data and wrote the following code to complete this little job.
#!/usr/bin/env python# -*- coding: utf-8 -*-#author  qingmiaoimport mysqldb  as mdbimport sysimport random,stringdef random_code (Code_length,code_long):     i=1    result = []    while i<= code_length:        salt =  '. Join (Random.sample ( String.ascii_letters + string.digits, code_long))          result.append (salt)         i=i+1    return  resultdef save_to_mysql (num_list):    try:         conn = mdb.connect ("127.0.0.1",  "root",  "root",  "test")          cur = conn.cursor ()          conn.select_db (' Test ')         sql_to_create_table =  ' create table if not  Exists active_code (Active_code char (+)) '         cur.execute (sql_to_create_table)         cur.executemany (' insert into  Active_code values (%s) ',  num_list)         conn.commit ()     except mdb. error, e:        print  "error %d: %s"  %  (E.args[0], e.args[1])         sys.exit (1)      finally:        if conn:             conn.close () if __name__ ==  ' __main__ ':     code_num = random_code (10,8)     save_to_mysql (code_num)

Finally go to the database to look at the data insertion effect:

Mysql> SELECT * from active_code;+-------------+| Active_code |+-------------+| Frokeoda | | ZMabDOn0 | | RJGKWCIB | | g18spxbx | | V8owjxyb | | iwFOBZx9 | | Ha1mcrin | | Ertnixbo | | X2A1BOGL | | Beblm3ki |+-------------+10 rows in Set (0.00 sec) mysql>


Python randomly generates a specified length string and saves it in MySQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.