惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Posts on Changkun's Blog

Why High-Output Systems Are Often the First to Stop Growing Dark Forest Theory: A Formal Derivation Agents (or Humans) in Goal-Directed and Goalless Environments: On Pipelines, Priors, and the Rhythm Between Exploration and Exploitation At the Boundary of Self-Reference: From Stable Structures in Artificial Intelligence to the Self as a Recursive Model in an Open Dissipative System 2023 Reading List 2022 Reading List 2021 Reading List Are PSS/USS and RSS Actually the Same Thing? Performance Differences from Page Faults vs. Prefetching 2020 Year-End Review Migration with Zero Downtime 2020 Reading List The All in Go Stack Pointers Might Not Be Ideal for Parameters Eliminating A Source of Measurement Errors in Benchmarks Setup Wordpress in 10 Minutes 我为什么不再写博客了? 2019 年终总结 2018-2019 读书清单 Ten years of blogging Rethinking the Reflections on Communications and Trusts 2018 年终总结 Go source code study is open source Go source study: unsafe Pattern Go source study: sync.Pool Go runtime programming A Million WebSocket and Go Designing Asynchronous RESTful APIs 分布式杂谈01:CAP 理论的误解 Issues of Human-Bot Interaction 压缩法与深度网络的泛化性 Go in 1 Hour UMSLT04: The Past and Present of SGD UMSLT03: A Gentle Start of Learning Theory UMSLT02: A Breif History of Neural Networks UMSLT01: A Breif History of Regularization 不笑不足以为道 论文笔记:Generalization in Deep Learning 2017 年终总结 2017 读书清单 深度学习的泛化理论简介 删除 GitHub 上已经提交的敏感信息 硕士生涯的第一年就这样告一段落了 人肉计算(10): 系统参与激励 人肉计算(9): 陷阱的解法 别聊,一聊你就暴露 人肉计算(8): 人肉计算与数据科学中的陷阱 人肉计算(7): 社会行为分析 Hexo + GitHub + Travis CI + VPS 自动部署 人肉计算(6): 预测市场 人肉计算(5): 信用风险评级模型 读书与回报 瞎扯: 对现代企业理论与当下IT企业的商业模式和信息产业链的规律性的思考 人肉计算(4): 输入数据聚合与PageRank 又一次打整了一下博客 人肉计算(3): 输入数据聚合与链路预测 人肉计算(2): 意图博弈 GWAPs 人肉计算(1): 众包与群众智慧 对后辈同学在计算机专业上的答疑与解惑 在德国的医疗及住院体验 这可能不是一个技术博客了 实验楼楼赛第3期-Python-题解 迅速更换了 DISQUS Electron 深度实践总结 良好的编码体验的三个方面 2016 年终总结 2016 读书清单 最近在着手写的文章 微信小程序文档极致总结 谈谈过去三个月在实验楼的实习经历 Built a Desktop Client for My Blog Guacamole 源码分析与 VNC 中 RFB 协议的坑 《高速上手 C++11/14》正式发布 Docker 极速入门教程02 - 镜像与容器管理 Docker 极速入门教程01 - 基本概念和操作 阶段性沉默 ELK+Redis 最佳实践 终于全面启用了 HTTPS 苹果开源了LZFSE无损压缩 Hash 碰撞的一种思路 记一次完整的 Kaldi-TIMIT 示例运行 Kaldi 上的 TIMIT 例子 Kaldi 安装与部署 从科研写作谈起 Swift API 设计指南 有趣的人类 所以其实论文并没有什么鬼用 Githug 通关记录及指南 小结一下这学期的收获 2015 读书清单 2015 年终总结 负能量爆表 转眼就快两个月了 博客迁移记录 大三总结 这个世界,终究不会是我们的。 Linux 内核分析 之六:Linux 内核创建进程的过程 小说「泽缘」 Linux 内核分析 之五:system_call中断处理过程的简要分析 大创项目的标题真是每年都在考验同学们的想象力啊
Python-MySQLdb 教程
Changkun Ou · 2014-11-06 · via Posts on Changkun's Blog

Published at发布于:   |   PV/UV: /   |   Reading阅读: 2 min

Python操作MySQL,一个常用的方案就是使用MySQLdb库,安装在之前的日志已经介绍过了: Mac下新安装的MySQL无法登陆root用户解决方法

下面我们来看看如何使用Python操作MySQL,基本逻辑分为四个步骤。

包含MySQLdb库

与MySQL建立连接

1
conn = MySQLdb.connet(host='localhost', user='root';, passwd='root", db = 'euryugasaki', port=3306)

connect()方法用来提供与MySQL的连接,接受多个参数,返回连接的对象: host: 数据库主机名,默认是本地主机 user: 数据库登录用户,默认是当前用户 passwd: 数据库登录密码,默认是空 db: 使用的数据库名,没有默认值 port: MySQL服务使用TCP端口,默认3306

连接对象提供了对事务操作的支持,标准方法有: commit() 提交 插入更新数据的时候一定要执行commit()否则不能真正的插入数据。 rollback() 回滚

运行SQL语句并接受返回值

1
2
cursor = conn.cursor()
n = cursor.execute(sql,param)

我们需要使用连接返回的对象获得一个cursor对象,并使用cursor提供的方法来进行工作。这类方法包括两大类: a) 执行命令 callproc(self, procname, args): 用来执行存储过程,接受的参数为存储过程名和参数列表,返回值为受影响的行数. execute(self, query, args): 执行单条SQL语句,接受的参数为SQL语句本身和使用的参数列表,返回值为受影响的行数. executemany(self, query, args): 执行单条SQL语句,但是重复执行参数列表里的参数,返回值为受影响的行数. nextset(self): 移动到下一个结果集 b) 接受返回值 fetchall(self):接受全部的返回结果行. fetchmany(self, size=None): 接受size调返回结果行,如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据 fetchone(self): 返回一条结果航 scroll(self, value, mode=‘relative’): 移动指针到某一行,如果mode=‘relative’,则表示当前所在行移动value条,如果mode=‘absolute’,则表示从结果集的一行移动value条

关闭数据库连接

需要分别关闭指针对象和连接对象,他们有名字相同的方法:

1
2
cursor.close()
conn.close()

例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import MySQLdb

try:
	connection = MySQLdb.connect(host='localhost', user='root', passwd='cvlabock', db = 'euryugasaki', port=3306)
	cur = connection.cursor()
	count = cur.execute('SELECT * FROM wp_users')

	#only accept one return value
	result = cur.fetchone()
	print result

	#accept five return values
	results = cur.fetchmany(5)
	for r in results:
		print r
	print "\n"

	#accept all the return values
	result2 = cur.fetchall()
	print result2

	#insert datas
	cur.execute('CREATE DATABASE IF NOT EXISTS testEuryugasaki')
	conn.select_db('testEuryugasaki')
        cur.execute('CREATE TABLE test(id int, info varchar(20))')
	value=[1, 'hi Longqi']
	cur.execute('INSERT INTO testEuryugasaki VALUES(%s, %s)', value)
	values=[]
	for i in range(20):
		values.append((i, 'hi Longqi '+str(i)))
	cur.excutemany('INSERT INTO testEueyugasaki VALUES(%s, %s)', values)
	cur.execute('UPDATE testEuryugasaki SET info="I am Euryugasaki" WHERE id = 3')

	conn.commit()

	cur.close()
	connection.close()

except MySQLdb.Error, e:
		print "MySQL Error %d: %s" % (e.args[0], e.args[1])

connet()方法中还有一个参数是charset,设置charset是让数据库的编码与自身相同,如果数据库的编码是gb2312,则使用charset=‘gb2312’,如果是utf-8则charset=‘urt8’