python查询mysql数据库_Python操作mysql之查询数据

学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.脚本如下#!/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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值