首页 > 代码库 > python3 使用pymysql
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 = 025 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 +=132 return a33 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。