mysql数据库连接操作
1、各大数据库操作文章:http://www.lemfix.com/topics/306
2、在python3中对接mysql数据库使用到的库为pymysql模块:
2.1、mysql数据库:pymysql模块
2.2、pymysql模块安装:pip install pymysql
3.数据库的操作步骤:
3.1、引入pymysql模块:import pymysql
3.2、建立连接,连接数据库:
cou = pymysql.connect(
host = 'xxxxxxx',
port = 3306,
user = 'xxxxxxx',
password = 'xxxxxxx',
database = 'xxxxxxx',
charset = 'utf8',
cursorclass = pymysql.cursors.DictCursor
)
3.2.1、创建游标
cur = cou.cursor()
3.3、执行对应的sql语句 方法:游标.execute(sql语句)
2.sql = 'select * from member LIMIT 4'
3.count = cur.execute(sql)
4.
3.4、获取sql语句执行后的数据结果
one = cur.fetchone()
print('第一条数据是:',one)
two = cur.fetchone()
print('第二条数据是:',two)
print('*************************************************')
all = cur.fetchall()
print('所有数据是:',all)
print('*************************************************')
3.5、关闭游标,关闭数据连接,资源释放
cur.close()
cou.close()
如何随机生成手机号码
'''
==================================
cooding:utf-8
@Time :2020/7/4 15:57
@Author :henry
@Email :yinpingwei@gmail.com
@File :随机生成手机号码.py
@Software:PyCharm
===================================
'''
'''
1.随机生成11位手机号,前三位+后8位
2.进行数据校验
'''
prefix = [133, 149, 153, 173, 177, 180, 181, 189, 199,
130, 131, 132, 145, 155, 156, 166, 171, 175, 176, 185, 186, 166,
134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 172, 178, 182, 183, 184, 187, 188, 198
]
import random
from py30.Public.Read_mysql_database import Read_mysql_db
def get_new_phone():
db = Read_mysql_db()
while True:
phone = __random_phone()
count = db.Obtain_count('select * from member where mobile_phone="{}"'.format(phone))
if count == 0:
db.close()
return phone
def __random_phone():
index = random.randint(0,len(prefix)-1)
phone = str(prefix[index])
for _ in range(0,8):
phone += str(random.randint(0,9))
return phone
print(get_new_phone())