Python MySQLdb 模块

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

[root@localhost ~]$ yum install -y MySQL-python    # 安装 MySQLdb 模块
In [1]: import MySQLdb

In [2]: conn = MySQLdb.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/10424729.html
今日推荐