0
点赞
收藏
分享

微信扫一扫

【Python之pymysql库学习】2.创建数据表(保姆级图文+实现代码)

目录


实现效果

在这里插入图片描述
在这里插入图片描述


实现思路

注意整体架构使用try-except进行排除异常

创建数据表


实现代码

# @Time    : 2021/12/14 20:01
# @Author  : 南黎
# @FileName: 2.创建数据表.py
import pymysql
try:
    #创建与数据库的连接
    #参数分别是 指定本机 数据库用户名 数据库密码 数据库名 端口号 autocommit是是否自动提交(非常不建议,万一出问题不好回滚)
    db=pymysql.connect(host='localhost',user='root',password='root',database='python',port=3306,autocommit=False)
    #创建游标对象cursor
    cursor=db.cursor()
    #使用execute()方法执行sql,如果表存在则删除
    cursor.execute('drop table if EXISTS student')
    #创建表的sql
    sql='''
        create table student(
        sno int(8) primary key auto_increment,
        sname varchar(30) not null,
        sex varchar(5) ,
        age int(2),
        score float(3,1)
        )
    '''
    cursor.execute(sql)
except:
    print('创建表失败')
finally:
    #关闭数据库连接
    db.close()

总结

大家喜欢的话,给个👍,点个关注!给大家分享更多有趣好玩的Python知识!

版权声明:

发现你走远了@mzh原创作品,转载必须标注原文链接

Copyright 2022 mzh

Crated:2022-1-15


举报

相关推荐

0 条评论