python操作mysql需要用到MySQLdb这个库。
1.下载MySQLdb,点击这里下载(可能被墙请自带梯子)
2.使用
import MySQLdb
try:
con = MySQLdb.connect(host='192.168.1.100', user='myuser', passwd='123456', port='3306', db='mydb',charset='utf8')
c = con.cursor()
c.execute('select * from user');
rows=c.fetchall() #一次读取所有数据,返回的数据结构[(?,?,...),(?,?,..),..]
for row in rows:
for column in row:
print column
except Exception,e:
print e
finally:
c.close()
con.close()
import MySQLdb
try:
con = MySQLdb.connect(host='192.168.1.100', user='myuser', passwd='123456', port='3306', db='mydb',charset='utf8')
c = con.cursor()
#使用占位符传递参数,参数是一个tuple
c.execute('select * from user where user=%s',('root'));
rows=c.fetchall() #一次读取所有数据,返回的数据结构[(?,?,...),(?,?,..),..]
for row in rows:
for column in row:
print column
except Exception,e:
print e
finally:
c.close()
con.close()
import MySQLdb
try:
con = MySQLdb.connect(host='192.168.1.100', user='myuser', passwd='123456', port='3306', db='mydb',charset='utf8')
c = con.cursor()
#使用占位符传递参数,参数是一个tuple
c.execute('update user set host=%s where user=%s',('root','192.168.1.200'));
con.commit() #更新操作记得提交事物,否则更改不会生效
except Exception,e:
print e
finally:
c.close()
con.close()
import MySQLdb
try:
con = MySQLdb.connect(host='192.168.1.100', user='myuser', passwd='123456', port='3306', db='mydb',charset='utf8')
c = con.cursor()
vs=[]
vs.append(('root','192.168.1.100'))
vs.append(('db','192.168.1.101'))
vs.append(('pdb','192.168.1.101'))
#使用占位符传递参数,参数是一个list tuple
c.executemany('insert into user(user,host)values(%s,%s)',vs);
con.commit() #更新操作记得提交事物,否则更改不会生效
except Exception,e:
print e
finally:
c.close()
con.close()
3.注意事项
咋看一下其中占位符和字符串格式化差不多,天真的以为数字用%d,浮点数用%f,字符串用%s,那你可以就要悲剧了
事实上这里的占位符只能是%s
分享到:
相关推荐
Python操作mysql数据库
python操作mysql数据库上课讲义.pdf
python操作mysql数据库.pdf
python操作mysql数据库.py
python操作mysql数据库的9个实例共11页.pdf.zip
主要介绍了Python操作MySQL数据库,结合实例形式详细分析了Python操作mysql数据库的安装、连接、增删改查等相关实现技巧与注意事项,需要的朋友可以参考下
python操作mysql数据库实现增删查改
python操作mysql数据库---精品管理资料.pdfpython操作mysql数据库---精品管理资料.pdf
python操作mysql数据库.docx
高级教程】课程列表01 Python语言开发要点详解.pptx02 Python数据结构.pptx03 Python函数和函数式编程.pptx04 Python面向对象编程.pptx05 Python数据采集 网络爬虫 网页爬虫.pptx06 Python操作MySQL数据库.pptx07 ...
python操作mysql数据库分享.pdf