前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MySQL | Python Hello World

MySQL | Python Hello World

作者头像
Zkeq
发布2022-05-18 14:58:24
2940
发布2022-05-18 14:58:24
举报
文章被收录于专栏:Zkeq

感谢 @xcsoft 大佬带小白入门…..

1
1

代码

代码语言:javascript
复制
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='py',
                             password='MsXMAFiaaSKRei6j',
                             database='py',
                             cursorclass=pymysql.cursors.DictCursor)

with connection:
    # Create a new cursor
    # 这个游标的意思,应该是跟鼠标差不多?
    with connection.cursor() as cursor:
        sql_create = """
                    CREATE TABLE `users` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `email` varchar(255) COLLATE utf8_bin NOT NULL,
                    `password` varchar(255) COLLATE utf8_bin NOT NULL,
                    PRIMARY KEY (`id`)
                    ) 
                    ENGINE=InnoDB 
                    DEFAULT 
                    CHARSET=utf8mb4 
                    COLLATE=utf8mb4_bin
                    AUTO_INCREMENT=1 ;
                    """
        # 首先建表
        cursor.execute(sql_create)
        # 只需要建表一次哦
        # Create a new record
        # 再执行语句
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
        # 执行完毕之后就关闭这个连接
    # connection is not autocommit by default. So you must commit to save
    # your changes.
    # 想要保存数据,就要提交?
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档