Python对mysql的操作三

本文介绍了一个使用Python连接MySQL数据库并进行表的创建、插入随机数据及查询操作的完整实例。通过自定义函数实现数据库连接,并演示了如何创建学生、课程等表结构,批量插入随机生成的数据,以及如何查询课程表中的所有记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1)创建表

import MySQLdb
def connect_mysql():
    db_config = {
        "host":"localhost",
        "user":"root",
        "passwd":"root",
        "db":"python_db",
        "charset":"utf8"
    }
    try:
        cnx = MySQLdb.connect(**db_config)
    except Exception as e:
        raise e
    return cnx
student = '''
    create table student(
        stdid int primary key not null,
        stdname varchar(100) not null,
        gender enum('F','M'),
        age int
    )
'''
course = '''
    create table course(
        couid int primary key not null,
        cname varchar(100) not null,
        tid int not null
    )
'''
sorce = '''
    create table sorce(
        sid int primary key not null,
        std int not null,
        couid int not null,
        grade int not null
    )
'''
teacher = '''
    create table teacher(
        tid int primary key not null,
        tname varchar(100) not null
    )
'''
tmp = '''
    set @a := 0;  # mysql中变量不用事前申明,直接用“set @变量名”就可以了
    create table tmp as select (@a := @a + 1)as id from information_schema.tables limit 10;
    # 当@a需要在select中使用的时候,必须加:
'''
if __name__ == '__main__':
    cnx = connect_mysql()
    cus = cnx.cursor()
    try:
        cus.execute(student)
        cus.execute(course)
        cus.execute(sorce)
        cus.execute(teacher)
        cus.execute(tmp)
        cus.close()
        cnx.commit()
    except Exception as e:
        cnx.rollback()
        raise e
    finally:
        cnx.close()

2)增加数据

# select * from tmp;  # 10条数据
# select * from tmp a,tmp b,tmp c;  # 1000条数据,相当于10*10*10

# 获得随机字符串的设计
# 增加的数据是随机数据, rand()函数随机生成一个0-1的随机数
# sha1()函数对数字进行加密,然后生成一堆字符串
# concat()是拼接多个字符串的函数
# substr()截取多少个字符

# 获得随机整数的设计
# rand()*50   获得0-50的随机小数
# floor() 这个函数代表的是去尾法取整数

# 男女的设计
# rand()*10  /2   最后取余数
# 如果余数为1,就设置为M
# 如果余数为0,就设置为F

student1 = '''
    set @b := 10000;
    insert into student select @b:= @b+1,substr(concat(sha1(rand()),sha1(rand())),1,5+floor(rand()*50)),case floor(rand()*10) mod 2 when 1 then 'M' else 'F' end,20+floor(rand()*8) from tmp a,tmp b,tmp c,tmp d;
'''
course1 = '''
    set @c := 10;
    insert into course select @c:= @c+1, substr(concat(sha1(rand()), sha1(rand())), 1, 5 + floor(rand() * 45)),  100 + floor(rand() * 100) from tmp a;
'''
sorce1 = '''
    set @d := 10000;
    insert into sorce select @d:= @d+1, floor(10001 + rand()*10000), floor(11 + rand()*10), floor(1+rand()*100) from tmp a, tmp b, tmp c, tmp d;
'''
theacher1 = '''
    set @e := 100;
    insert into teacher select @e:= @e+1, substr(concat(sha1(rand()), sha1(rand())), 1, 5 + floor(rand() * 80)) from tmp a, tmp b;
'''

3)查询数据

import codecs
import MySQLdb
def connect_mysql():
    db_config = {
        'host': 'localhost',
        'port': 3306,
        'user': 'root',
        'passwd': 'root',
        'db': 'python_db',
        'charset': 'utf8'
    }
    cnx = MySQLdb.connect(**db_config)
    return cnx

if __name__ == '__main__':
    cnx = connect_mysql()
    sql = '''select * from course;'''
    #sql = '''select * from student where stdname in (select stdname from student group by stdname having count(1)>1 ) order by stdname;'''
    try:
        cus = cnx.cursor()
        cus.execute(sql)
        result = cus.fetchall()
        with codecs.open('select.txt', 'w+') as f:
            for line in result:
                f.write(str(line))
                f.write('\n')
        cus.close()
        cnx.commit()
    except Exception as e:
        cnx.rollback()
        print('error')
        raise e
    finally:
        cnx.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值