Python爬虫数据存储MySQL【1】连接方式
16lz
2021-01-22
环境 python2.7+Win
1.安装MySQldb模块
访问:http://www.lfd.uci.edu/~gohlke/pythonlibs/
下载MySQL_python-1.2.5-cp27-none-win_amd64.whl(32位64位自行选择)
将其拷贝到python安装目录下的Scripts目录下,在文件位置打开cmd,执行pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
验证,python(command line)输入import MySQLdb,没报错,说明安装成功。
参考:http://blog.csdn.net/fgwvip123/article/details/52382521
2.Python操作MySQL数据库
# -*- coding: UTF-8 -*-
# 基本操作
import MySQLdb
# 打开数据库连接,首先需要创建一个test数据库
db = MySQLdb.connect("127.0.0.1","账号","密码","test")
# 使用cursor方法获取操作光标,cursor(光标)
cursor = db.cursor()
# 使用execute方法执行sql语句,execute(执行)
cursor.execute("select version()")
# fetch(获取)one,all
data = cursor.fetchone()
print "Database version: %s" % data
# -*- coding: UTF-8 -*-
# 插入数据
import MySQLdb
name = "testname"
password = "testpasss"
# 打开数据库连接,首先需要创建一个test数据库
db = MySQLdb.connect("127.0.0.1","账号","密码","test")
# 使用cursor方法获取操作光标,cursor(光标)
cursor = db.cursor()
# sql语句
sql = '''insert into user(name, password)
values ("%s", "%s")''' % (name,password)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误,未commit之前回滚
db.rollback()
db.close()
参考:
菜鸟教程:http://www.runoob.com/python/python-mysql.html
官方手册:http://mysql-python.sourceforge.net/MySQLdb.html
更多相关文章
- python数据存储系列教程——python中mysql数据库操作:连接、增删
- 请问图片存到MySQL服务器中的时候如何操作?
- mysql数据库基本操作指南
- python操作mysql 抛出Unread result found的处理方法
- [置顶] SQL0668N 原因码为 "1",所以不允许操作 SQLSTATE=5
- MySQL学习总结----数据操作
- SQL基本操作 - 新增、查看、更新、删除表中数据
- SQL当执行插入操作时,字符串含有''的时候的处理
- mysql数据库之表的操作