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

pymysql

时间:2018-01-18 15:05:23      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:etc   man   str   strong   行数据   comm   div   exec   3.3   

一、pymysql

  pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,我们今天来说下pymsql用法。MySQLdb的只有在python2 里面使用的,在python3里面需要用pymysql。

二、安装pymysql

pip3 install pymysql

 

三、使用

  3.1 连接mysql

# -*- coding: UTF-8 -*-

import pymysql

#  创建连接
conn = pymysql.connect(host=‘172.16.200.49‘, port=3306,
                       user=‘bigberg‘, password=‘111111‘,
                       db=‘study‘)

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

# 执行SQL,并返回受影响行数
effect_row = cursor.execute("select * from student")
print(effect_row)
# 执行SQL,并返回受影响行数
# data = [
#     (‘S1‘,‘2018-04-21‘,‘M‘),
#     (‘S2‘,‘2018-05-11‘,‘F‘),
#     (‘S3‘,‘2018-04-25‘,‘M‘)
# ]
# sql = "insert into student (name,register_date,gender) values (%s,%s,%s)"
# effect_row = cursor.executemany(sql,data)
# 提交,不然无法保存
conn.commit()

# 关闭游标
cursor.close()

# 关闭连接
conn.close()

  3.2 获取查询的数据

# -*- coding: UTF-8 -*-

import pymysql

#  创建连接
conn = pymysql.connect(host=‘172.16.200.49‘, port=3306,
                       user=‘bigberg‘, password=‘111111‘,
                       db=‘study‘)

cursor = conn.cursor()
sql = "select * from student where stu_id>3"
cursor.execute(sql)
# 获取第一行数据
# result = cursor.fetchone()

# 获取前n条数据
# result = cursor.fetchmany(3)

# 获取所有数据
result = cursor.fetchall()
print(result)

conn.commit()
cursor.close()
conn.close()

  3.3 fetch数据类型

import pymysql

#  创建连接
conn = pymysql.connect(host=‘172.16.200.49‘, port=3306,
                       user=‘bigberg‘, password=‘111111‘,
                       db=‘study‘,)
# 游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

  

 

pymysql

标签:etc   man   str   strong   行数据   comm   div   exec   3.3   

原文地址:https://www.cnblogs.com/bigberg/p/8310063.html

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