-
需要安装第三方库pymysql
方法一:通过pip安装pymysql
(pip install/uninstall pymysql)方法二:通过安装文件
github地址 https://github.com/PyMySQL/PyMySQL
python setup.py install -
pymysql库的基本使用
#!/usr/bin/python
#coding=utf-8
import pymysql
# 创建连接
# conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='exam', charset='utf8')
# 创建游标
# cursor = conn.cursor()
######## 执行SQL ########
# 执行SQL,并返回收影响行数
# select_row = cursor.execute("select * from python_db limit 3")
# 执行SQL,并返回受影响行数
# update_row = cursor.execute("update python_db set names = '中文' where id = 1")
# 执行SQL,并返回受影响行数,执行多次
# insert_row = cursor.executemany("insert into python_db (names) values (%s)", [("u1pass"),("u2pass")])
######## 获取查询数据 ########
# cursor.execute("select * from python_db")
# 获取查询结果的第一行数据
# first_row = cursor.fetchone()
# 获取查询结果的前n行数据
# num_row = cursor.fetchmany(3)
# 获取查询结果的所有数据
# all_row = cursor.fetchall()
######## 获取新创建数据自增ID ########
# cursor.executemany("insert into python_db (names) values (%s)", [("123"),("456"),("789")])
# 获取最新一条自增id
# new_insert_id = cursor.lastrowid
######## 数据类型由元祖类型转换为字典类型 ########
# conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='exam', charset='utf8')
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# cursor.execute("select * from python_db")
# all_row = cursor.fetchall()
######## 提交关闭mysql ########
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
############参考文档 https://www.cnblogs.com/wt11/p/6141225.html
网友评论