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