Python操作mysql数据库,,学python好久了


学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/envpython#-*-coding:utf-8-*-‘‘‘Date:2016-11-08Auther:Bob‘‘‘importMySQLdbdefpython_mysql_query():#Openthedatabaseconnectiondb=MySQLdb.connect(host=‘localhost‘,user=‘ossec‘,passwd=‘mysql0123‘,db=‘ossec‘,port=3306,charset=‘utf8‘)#Getstheoperationcursorcursor=db.cursor()#SQLstatementquery#sql="select*fromdatawhereid<‘%d‘"%(5)sql="select*fromdatalimit5"try:#ExecutetheSQLstatementcursor.execute(sql)#Receiveallreturnresultsresults=cursor.fetchall()#Traversetheprintlistforiinresults:printiexcept:print"Error:unabletofecthdata"#Closethecursorcursor.close()#Closethedatabaseconnectiondb.close()if__name__==‘__main__‘:python_mysql_query()

本文出自 “卡卡西” 博客,请务必保留此出处http://whnba.blog.51cto.com/1215711/1870648

Python操作mysql数据库

评论关闭