學python很久了,也沒寫過腳本,先來個mysql數據庫的查詢腳本吧.
python
1.首先要安裝MySQLdbmysql
[root@python ~]# pip install MySQL-pythonsql
Collecting MySQL-python數據庫
Downloading MySQL-python-1.2.5.zip (108kB)ide
100% |████████████████████████████████| 112kB 171kB/s fetch
Building wheels for collected packages: MySQL-pythonui
Running setup.py bdist_wheel for MySQL-python ... donespa
Stored in directory: /root/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62ip
Successfully built MySQL-pythonutf-8
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()