码迷,mamicode.com
首页 > 数据库 > 详细

python3 使用pymysql

时间:2016-09-04 18:58:20      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

 

 

 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%等也应用引号区分)

 

python3 使用pymysql

标签:

原文地址:http://www.cnblogs.com/hb91/p/5839833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!