Python pymysql 模块

pymysql 是 Python3 连接 MySQL 的一个模块,常见用法如下:

[root@localhost ~]$ pip3 install pymysql    # 安装 pymysql 模块
In [1]: import pymysql

In [2]: conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456')    # connect()用于连接MySQL数据库,结果返回一个连接对象
                                                                                  # 常用的连接参数有:host 、user 、passwd 、db 、port
In [3]: cur = conn.cursor()               # 创建游标,用来存放执行SQL语句所检索出来的结果集

In [4]: cur.execute('show databases')     # 使用游标来执行SQL语句,8L表示结果有8行,结果会存存储在游标中
Out[4]: 8L

In [5]: cur.fetchone()
Out[5]: ('information_schema',)           # fetchone()用于查看一条结果

In [6]: cur.fetchmany(3)
Out[6]: (('mysql',), ('performance_schema',), ('test',))    # fetchmany()用于查看多条结果

In [7]: cur.fetchall()
Out[7]: (('test1',), ('test2',), ('test3',), ('wordpress',))    # fetchall()用于查看所有结果

In [7]: conn.close()    # 关闭连接

    

    

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10447637.html