学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-08Author:Bob'''import MySQLdbdef 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()