20171031 python访问MySQL

1. 基本流程

Paste_Image.png

2. 连接到数据库

Paste_Image.png

3. connection对象的方法

Paste_Image.png

4. cursor对象的方法

Paste_Image.png

5. 通用的示例代码

# -*- coding: utf-8 -*-
# @Time    : 2017/10/31 13:43
# @Author  : 李绍俊
# @Email   : 188792829@qq.com
# @File    : testMySQL.py


import MySQLdb as con

cnx = con.connect(host = 'localhost',
                  port = 3306,
                  user='root',
                  passwd='supermap',
                  database='test03',
                  charset = 'utf8')

cur = cnx.cursor()

tbName = '员工表'

try:
    cur.execute(f"drop table if EXISTS {tbName}")
    cur.execute(f"create table {tbName}(编号 varchar(10), b int, c int)")



    for i in range(200):
        strSQL = f"insert into {tbName} values('中文测试',{i},{i})"
        cur.execute(strSQL)

    cnx.commit()
except Exception as e:
    print(e)
    cnx.rollback()


cur.execute(f"select * from {tbName}")

# for row in cur.fetchall():
#     print(row)

print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())

print(cur.fetchmany(3))

print(cur.fetchall())

cur.close()

cnx.close()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,198评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,143评论 25 709
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,823评论 18 399
  • 01 我的母亲是一位典型的农村妇女,小时候没上过学,到现在也不会写出自己的名字。 母亲一生任劳任怨,敦厚善良。我清...
    潮派妈妈阅读 401评论 0 2
  • “想象力比知识更重要,因为知识局限于我们已经知道和理解的事物,而想象力拥抱整个宇宙,和我们未来希望知道和理解的所有...
    姜月萍阅读 115评论 0 0