Learn python for a long time, did not write a script, first a MySQL database query script it.
1. To install MYSQLDB first
[[Email protected] ~]# 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. The script is as follows
#!/usr/bin/env python# -*- coding: utf-8 -*-' Date:2016-11-08auther: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 ()
This article is from "Kaka West" blog, please be sure to keep this source http://whnba.blog.51cto.com/1215711/1870648
Python operation MySQL Database