Lanms Blog

pymysql应用
Publish: 2019/3/29   

ORM - Object Relation Mapping 对象关系映射

关键字

host / [port] / user / passwd / db / charset / [autocommit / cursorclass=pymysql.cursors.DictCursor]

操作方法
  1. 调用的是pymysql的connect()/Cursor()方法
  2. 创建连接 pymysql.connect() 输入
import pymysql
conn = pymysql.connect(host='localhost', port=3306,user='root', passwd='123456', db='hrs',charset='utf8', autocommit=False)
  1. 创建Cursor()
    • cursor.execute() 执行sql语句
try:
    with conn.cursor() as cursor:
        result = cursor.execute('insert into tbdept values ()')
        conn.commit()
finally:
    conn.close()

# 安全占位符
result = cursor.execute('insert into tbdept values (%s, %s, %s)',(dno, dname, dloc))
# 命名占位 
result = cursor.execute('insert into tbdept values (%(no)s, %(name)s, %(dloc)s)', {'no': dno, 'name': dname, 'loc': dloc})

用 select + fetchone() 对查找内容进行输出

    try:
        with conn.cursor() as cursor:
            # 一般不适用 * 查询 ,
            cursor.execute('select dno, dname, dloc from tbdept')
            result = cursor.fetchone()
            while result:    # fetchone 每次抓去一条出来
                print(result[1])
                result = cursor.fetchone()
            conn.commit()
    finally:
        conn.close()

常见的报出的错误

Cannot connect… host 错误 port 错误 服务器没有启动

Access denied … -user/ -passwd错误

Unknown database …. 数据库名字写错

MySQL syntax Error / unknow … SQL 语句错误

默认情况root 只能本地连接,不能远程连接, 如果出现远程连接错误时, 将数据库的主机改为 %



← 深入了解Mysql 设计模式简介 →

Powered by Hexo, Theme designs by @hpcslag.
Style-Framework Tocas-UI designs by @yamioldmel