mysql

mysql

import pymysql
1.连接数据库

conn = pymysql.connect(host='localhost',
                       user='root',
                       password='redhat',
                       db='westos',
                       charset='utf8'
)

2.创建游标对象

cur = conn.cursor()

3.对数据库操作

######创建数据表#############
try:
    create_sqli = 'create table hello (id int,name varchar(30));'
    cur.execute(create_sqli)
except Exception as e:
    print('创建数据表失败:',e)
else:
    print('创建数据成功')

插入多条数据

try:
    info = [(i,i) for i in range(100,1000)]
    # 第一种方式
    # inser_sqli = "insert into hello values(%d,'%s');"
    # for item in info:
    #     print('insert语句:',inser_sqli %item)
    #     cur.execute(inser_sqli %item)
    # 第二种方式
    inser_sqli = "insert into hello values('%s','%s');"
    cur.executemany(inser_sqli,info)
except Exception as e:
    print('插入多条数据失败:',e)
else:
    print('插入多条数据成功')

查询数据库

sqli = ‘select * from hello’
默认不返回查询结果集 返回的是数据记录数

result = cur.execute(sqli)
print(result)
a= cur.fetchone()
print(a)

获取下一条查询结果集

print(cur.fetchone())

== 获取指定个数查询结果集==

print(cur.fetchmany(4))
info = cur.fetchall()
print(info)

在这里插入图片描述

print(cur.fetchmany(3))
# print('移动到指针最开始的地方...')
# cur.scroll(0,'absolute')
# print(cur.fetchmany(3))
# print(cur.fetchmany(2))
# print(cur.fetchall())
cur.scroll(-2,mode='relative')
print(cur.fetchmany(2))

练习

在这里插入图片描述

import random
from random import choice as choice
import string
import pymysql
# 生成指定位数密码, 前 n-1 位为数字, 最后一位为密码 ;
def create_passwd(count=6):
    nums = random.sample(string.digits, count - 1)
    letters = random.sample(string.ascii_letters, 1)
    return "".join(nums + letters)
a = create_passwd()
print(a,type(a))
# 生成随机的姓名, 有两个或三个汉字组成 ;
def create_name():
    first = ['许', '张', '赵', '钱', '孙', '李', '朱', '杨']
    second = ['彬', '群', '宁', '盼', '龙', '欢', '丹']
    last = ['彬', '群', '宁', '盼', '龙', '欢', '丹', ' ' ]
    name = choice(first) + choice(second)+ choice(last)
    return name.rstrip()
def main():
     # 1.连接数据库 host user passwd charset
     conn = pymysql.connect(host='localhost',
                        user='root',
                        password='redhat',
                        db='westos',
                        charset='utf8'
     )

     # 2.创建游标对象
     cur = conn.cursor()
     n = int(input("生成数据数:"))
     # 往数据库表中插入 n 条随机数据 ;
     for i in range(n):
     # cur.execute('insert into userinfo values("user1", "123");')
         sqli = 'insert into userinfo values ("%s", "%s");' %(create_name(), create_passwd())
         cur.execute(sqli)
         # 提交数据,并关闭连接 ;
     conn.commit()
     cur.close()
main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值