Python操作mysql之查询数据
2016-11-08 15:04
411 查看
学python好久了,也没写过脚本,先来个mysql数据库的查询脚本吧.
1.首先要安装MySQLdb
[root@python ~]# pip install MySQL-python
Collecting MySQL-python
Downloading MySQL-python-1.2.5.zip (108kB)
100% |████████████████████████████████| 112kB 171kB/s
Building wheels for collected packages: MySQL-python
Running setup.py bdist_wheel for MySQL-python ... done
Stored in directory: /root/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
2.脚本如下
1.首先要安装MySQLdb
[root@python ~]# pip install MySQL-python
Collecting MySQL-python
Downloading MySQL-python-1.2.5.zip (108kB)
100% |████████████████████████████████| 112kB 171kB/s
Building wheels for collected packages: MySQL-python
Running setup.py bdist_wheel for MySQL-python ... done
Stored in directory: /root/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
2.脚本如下
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Date:2016-11-08 Author:Bob ''' import MySQLdb def python_mysql_query(): #Open the database connection db = MySQLdb.connect(host='localhost',user='ossec',passwd='mysql0123',db='ossec',port=3306, charset='utf8') #Gets the operation cursor cursor = db.cursor() #SQL statement query #sql = "select * from data where id < '%d'" % (5) sql = "select * from data limit 5" try: #Execute the SQL statement cursor.execute(sql) #Receive all return results results = cursor.fetchall() #Traverse the print list for i in results: print i except: print "Error: unable to fecth data" #Close the cursor cursor.close() #Close the database connection db.close() if __name__ == '__main__': python_mysql_query()
相关文章推荐
- Python3操作MySQL,查询数据并保存到文件中
- mysql常用基础操作语法(六)--对数据排序和限制结果数量的条件查询【命令行模式】
- Python操作Mysql实例代码教程在线版(查询手册)
- MySQL数据记录基本操作——单表查询
- python操作mongodb根据_id查询数据的实现方法
- python操作mysql(三)查询
- python3-操作SQLite、创建表、添加数据、查询数据
- python使用peewee实现mysql数据操作
- 史上最简单的 MySQL 教程(二十五)「数据的高级操作 之 查询(下)」
- python 操作mysql数据中fetchone()和fetchall()
- Python操作Mysql实例代码教程(查询手册)
- python操作mysql基础之分割与合并数据
- 史上最简单的 MySQL 教程(二十三)「数据的高级操作 之 查询」
- MySQL--操作数据表3:记录查询(SELECT)【LIMIT】
- 用python简单实现类似thinkphp的针对Mysql操作的数据模型
- 用Python 模块xlrd 操作excel,并将数据导入MySQL
- 通过python将MySQL,Oracle查询的数据存到Excel文件
- Python 2.7_初试连接Mysql查询数据导出到excel_20161216
- python操作mysql——插入、查询、删除
- 史上最简单的 MySQL 教程(二十四)「数据的高级操作 之 查询(中)」