python 实现mysql 查询
2016-08-25 23:28
435 查看
要想使Python可以操作MySQL数据库,首先需要安装MySQL-python包,在CentOS上可以使用一下命令来安装
啥都不说了,走两步吧,下面的程序创建了一个到mysql数据库的连接,然后执行了一个简单的查询,并打印查询结果
下面看一个数据库建表和插入操作
下面再来看看查询,查询通常有两种方式:一种是使用cursor.fetchall()获取所有查询结果,然后再一行一行的迭代;另一种每次通过cursor.fetchone()获取一条记录,直到获取的结果为空为止。看一下下面的例子:
$ sudo yum install MySQL-python
啥都不说了,走两步吧,下面的程序创建了一个到mysql数据库的连接,然后执行了一个简单的查询,并打印查询结果
import MySQLdb conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong") cursor = conn.cursor () cursor.execute ("SELECT VERSION()") row = cursor.fetchone () print "MySQL server version:", row[0] cursor.close () conn.close ()
下面看一个数据库建表和插入操作
import MySQLdb conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong") cursor = conn.cursor () cursor.execute (""" CREATE TABLE TEST ( ID INT, COL1 VARCHAR(40), COL2 VARCHAR(40), COL3 VARCHAR(40) ) """) cursor.execute (""" INSERT INTO TEST (ID, COL1, COL2, COL3) VALUES (1, 'a', 'b', 'c'), (2, 'aa', 'bb', 'cc'), (3, 'aaa', 'bbb', 'ccc') """) conn.commit() cursor.close () conn.close ()
下面再来看看查询,查询通常有两种方式:一种是使用cursor.fetchall()获取所有查询结果,然后再一行一行的迭代;另一种每次通过cursor.fetchone()获取一条记录,直到获取的结果为空为止。看一下下面的例子:
import MySQLdb conn = MySQLdb.connect (host = "172.17.23.121", user = "fkong", passwd = "fkong", db = "fkong") cursor = conn.cursor () cursor.execute ("SELECT * FROM TEST") rows = cursor.fetchall() for row in rows: print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) print "Number of rows returned: %d" % cursor.rowcount cursor.execute ("SELECT * FROM TEST") while (True): row = cursor.fetchone() if row == None: break print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) print "Number of rows returned: %d" % cursor.rowcount cursor.close () conn.close ()
相关文章推荐
- 安装与配置Mysql数据库-python 实现mysql 查询
- python 实现mysql分页查询 小练习
- python 实现元组中的的数据按照list排序, python查询mysql得到的数据是元组格式,按照list格式对他们排序
- MySQL集群:主从数据库配置 实现查询负载
- 利用ErlyDB、Mysql来实现表的添加、删除、修改、查询操作
- MySQL中如何实现Top N及M至N段的记录查询?
- MySQL中如何实现Top N及M至N段的记录查询?
- MySQL中如何实现Top N及M至N段的记录查询?
- PHP+Mysql+jQuery实现查询和列表框选择操作
- 利用MySQL的一个特性实现MySQL查询结果的分页显示
- MySQL分表实现上百万上千万记录分布存储的批量查询设计模式
- MySQL 随机查询数据与随机更新数据实现代码
- Python使用Com组件及Access查询分析类实现
- MySQL 随机查询数据与随机更新数据实现代码
- [mysql] mysql 在update中实现子查询的方式
- 一个 MYSQL的存储过程 实现基于树型子结点的查询
- php实现的MySQL通用查询程序
- php实现的MySQL通用查询程序
- 在ORACLE、MSSQL、MYSQL中树结构表递归查询的实现方法
- 利用MySQL的一个特性实现MySQL查询结果的分页显示