码迷,mamicode.com
首页 > 数据库 > 详细

Python 操作 MySQL

时间:2018-03-30 01:13:30      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:http   row   cal   HERE   int   准备   模块   关闭   sel   

1. 准备工作

  • 安装pymysql: pip3 install pymysql
  • pymysql是专门用于操作MySQL的python模块;

2. 操作MySQL

# 示例:
import pymysql

# 创建连接
conn = pymysql.connect(host='local', port=3306, user='root', passwd='root', db='test', charset='utf8')

# 创建游标
cursor = conn.cursor()

# 执行SQL, 并返回影响行数
effect_row = cursor.execute("update hosts set host = '1.1.1.3'")

# 执行SQL, 并返回影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL, 并返回受影响行数
# effect_row = cursor.executemany(
#    "insert into hosts(host, color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 查询
r = cursor.execute('select * from student')
print(r)
# 从查询结果中获取所有数据
print(cursor.fetchall())    # 结果为元组
print(cursor.fetchone())    # 获取结果中的第一条数据

# 关闭游标
cursor.close()

# 关闭连接
conn.close()


参考资料:

Python 操作 MySQL

标签:http   row   cal   HERE   int   准备   模块   关闭   sel   

原文地址:https://www.cnblogs.com/linkworld/p/8673375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!