pzk7788

MySQLdb 是 Python2 连接 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 [8]: cur.close()     # 关闭游标

In [9]: conn.close()    # 关闭数据库连接

 

 

 

 

 

 

 

    

分类:

技术点:

相关文章: