python3 使用pymysql

 

 

 1 #! /usr/bin/env python3
 2 # coding = utf-8
 3 
 4 import random
 5 import pymysql
 6 
 7 
 8 # 连接数据库函数
 9 def connDB(data):
10     conn = pymysql.connect(host='localhost',user='root',passwd='#######',db='test',)  #数据库
11     cur = conn.cursor()   #游标
12     cur.execute('create database if not exists test;')   #执语句行
13     cur.execute('create table if not exists test1(id INT NOT NULL, num VARCHAR(40) );')
14     for i in range(len(data)):
15         cur.execute('insert into test1 (id,num) values("{0}","{1}");'.format(i,data[i]))   #{0} {1} 要和sql语句区分
16     cur.close()  #关游标
17     conn.commit()
18     conn.close()  #关数据库
19 
20 # 产生激活码
21 def make_number(num,length):
22     lstr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
23     a = []
24     cnt = 0
25     while cnt < num:
26         a_str = ''
27         for j in range(length):
28             a_str += random.choice(lstr)
29         if a_str not in a:
30             a.append(a_str)
31             cnt +=1
32     return a
33 
34 
35 if __name__ == "__main__":
36     nums = make_number(100,20)
37     print(nums)
38     connDB(nums)

 

错误处理:

pymysql.err.InternalError: (1054, "Unknown column 'K0F3hNCZUrXIA4wMEk6a' in 'field list'")

{0} {1} 要和sql语句区分,所以在该语句中用双引号标注,其他格式化字符串(d%,s%等也应用引号区分)

 

posted @ 2016-09-04 17:37  hb91  阅读(2400)  评论(0编辑  收藏  举报