python与MySQL的简单交互
下载MySQLdb模块:
sudo apt-get install python-MySQLdb
进入mysql:
mysql -uroot -p(需要密码的进入方式,如果没有设置密码:mysql -uroot即可)
连接MySQL
>>> import MySQLdb >>> conn = MySQLdb.connect(host='localhost',user='root',passwd='123',db='test') #连接MySQL >>> cur = conn.cursor() >>> cur.execute('show tables;') 0L #cur.execute('查询语句等') >>> cur.close() >>> conn.close()
#关闭
cursor用来执行命令的方法:
callproc(self,procname,args):用来执行存储过程,接受的参数为存储过程名和参数列表
execute(self,query,agrs):执行单条sql语句,接受参数为sql语句本身和使用参数列表
executemany(self,query,agrs):执行单条sql语句,但是重复执行参数列表里的参数
next(self):移动到下一个结果集
cursor用来接受返回值的方法:
fetchall(self):接受全部的返回结果
fetchmany(self,size=None):接受siez条返回结果行,如果size的值大于返回的结果行的数量,
则会返回cursor.aarraysiez条数据
fetchone(self):返回一条结果行
scroll(self,value,mode=relative):移动到某一行

浙公网安备 33010602011771号