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

Python pymysql模块学习心得

时间:2018-01-26 20:59:41      阅读:404      评论:0      收藏:0      [点我收藏+]

标签:exe   must   tab   心得   pymysql   print   地址   int   pass   

PyMySQL包含了一个纯Python的MySQL客户端的库,它的目的是用来替换MySQLdb,并且工作在CPython,PyPy和IronPython。

PyMySQL官方地址:https://pypi.python.org/pypi/PyMySQL#documentation

下面是一个简单的例子和说明:

dbInfo={
    host: host_IP,
    port: 3306,
    user: user_name,
    password: password,
     db: db_name,
     charset: utf8,}
def queryMysql(sql):

#将数据库的信息当成字段传给connect(),这样方便数据和函数分离,也可以直接在connect()里面写出参数 conn
= pymysql.connect(**dbInfo)
#建立连接后创建游标 cur
= conn.cursor()
#执行sql语句,select语句还需要fetch才能拿到数据,否则返回的是数据个数 cur.execute(sql) res
=cur.fetchall() cur.close()
#sql语句不是自动提交的,需要手动提交才能保持修改 conn.commit()
#执行sql语句后关闭连接 conn.close()
return res sql=select * from table_name result=queryMysql(sql) print(result)

下面是官方文档的例子,说明已经很详细了,我再简单补充一下:

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host=localhost,
                             user=user,
                             password=passwd,
                             db=db,
                             charset=utf8mb4,
                             cursorclass=pymysql.cursors.DictCursor)#cursorclass选择返回数据的格式,字典或者列表。
#try语句防止出现assert中断
try:
    #使用with语句可以免去关闭connection的操作
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, (webmaster@python.org, very-secret))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, (webmaster@python.org,))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

Python pymysql模块学习心得

标签:exe   must   tab   心得   pymysql   print   地址   int   pass   

原文地址:https://www.cnblogs.com/frost-hit/p/8361014.html

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