快速熟悉python 下使用mysql(MySQLdb)
首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看)
这里简单记录一下自己使用的学习过程:
一、连接数据库
MySQLdb提供了connect函数,使用如下
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
这里的参数的意义都是很明确的,但是这些参数并不是都是必须的:
1、host参数表示的是数据库所在地址,默认值是localhost,也就是说本机运行这个参数可以不指定
2、user、passwd 数据库的用户名和密码,必须存在
3、db 选择你要操作的数据库名,这个可以稍后指定,非必须
4、port 端口号,默认值3306
5、charset 用来指定字符集(默认utf8)
二、操作数据库
1、某些对象可以直接使用query(但是不推荐使用(所以这里基本略过),即使是使用也一定要先判断是否存在这个属性)
cxn.query('sql语句')
2、使用cur
cur=cxn.cursor()
这样我们就能使用cur执行各种操作了,示例代码如下:
import MySQLdb
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
cur=cxn.cursor()
result=cur.execute('select * from students')
for i in cur.fetchall():
print i
这段代码就能返回表students中的所有信息了,也就是你进入mysql输入select * from students之后所显示的内容。这里我就假设大家都了解sql的语句 使用了(不了解的可以去学或者用ORM操作数据库)
接下来我们演示一下怎么更新表,以怎么向表中插入数据为例:
import MySQLdb
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
cur=cxn.cursor()
def showtables(tname):
result=cur.execute('select * from %s'%tname)
for i in cur.fetchall():
print i
showtables('students')
cur.execute("insert into students values(4,'liu4',100)")
print 'after insert'
showtables('students')
这样我们会可以看待结果:
(1L, 'liu', Decimal(''))
(2L, 'liu2', Decimal(''))
(3L, 'liu3', Decimal(''))
after insert
(1L, 'liu', Decimal(''))
(2L, 'liu2', Decimal(''))
(3L, 'liu3', Decimal(''))
(4L, 'liu4', Decimal(''))
看似是一摸一样的完成了这项工作,但是这时候我们用终端连上mysql。执行一条select * from students却发现我们插入的那条并没有进去。这是因为 我们还缺少一个commit工作。另外工作完成之后我们需要关闭与数据库的连接,于是更改代码如下
import MySQLdb
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
cur=cxn.cursor()
def showtables(tname):
result=cur.execute('select * from %s'%tname)
for i in cur.fetchall():
print i
showtables('students')
cur.execute("insert into students values(4,'liu4',100)")
cxn.commit()
print 'after insert'
showtables('students')
cur.close()
cxn.close()
三、获取返回值
上面我们是将查询的结果都存在了一个result变量里的,比呢切返回的都是tuple。但是cursor还有若干方法:来接收返回值
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的 第一行移动value条.
四、批量执行和参数
使用MySQLdb我们不仅可以执行一条语句,更可以将他与python结合起来,这样我们就可以批量操做了
import MySQLdb
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
cur=cxn.cursor()
def showtables(tname):
result=cur.execute('select * from %s'%tname)
for i in cur.fetchall():
print i
showtables('students')
v=[]
for i in range(10):
v.append((i,'liu'+str(i),98))
cur.executemany("insert into students values(%s,%s,%s)",v)
cxn.commit()
print 'after insert'
showtables('students')
cur.close()
cxn.close()
上面用到了两处参数,第五行和第12行
另外当执行多个命令要用executemany(op,args)它类似 execute() 和 map() 的结合, 为给定的每一个参数准备并执行一个数据库查询/命令
五、零碎
上面说过db这个属性可以在连接之后指定,如下:
cxn.select_db('students')
快速熟悉python 下使用mysql(MySQLdb)的更多相关文章
- python下操作mysql 之 pymsql
python下操作mysql 之 pymsql pymsql是Python中操作MySQL的模块, 下载安装: pip3 install pymysql 使用操作 1, 执行SQL #!/usr/ ...
- python下的MySQL数据库编程
https://www.tutorialspoint.com/python/python_database_access.htm if you need to access an Oracle dat ...
- 记录一次从txt文件导入数据的python下的MySQL实现
环境: python2.7 ComsenzXP自带MySQL 安装python-MySQL模块 数据格式:txt格式的账号信息. 数据一行一条数据. 难点:有的行只有账号,没有密码:有的为空行:有的行 ...
- python下对mysql数据库的链接操作
参考网址: https://blog.csdn.net/guofeng93/article/details/53994112 https://blog.csdn.net/Chen_Eris/artic ...
- Python中的MySQL接口:PyMySQL & MySQLdb
MySQLdb模块只支持MySQL-3.23到5.5之间的版本,只支持Python-2.4到2.7之间的版本 PyMySQL支持 Python3.0以后的版本 PyMySQL https://pypi ...
- python学习之-- mysql模块和sqlalchemy模块
简单介绍python下操作mysql数据库模块有2个:pyhton-mysqldb 和 pymysql 说明:在python3中支持mysql 的模块已经使用pymysql替代了MysqlDB(这个 ...
- Python基础(三)Mysql数据库安装及使用
在python下使用mysql需要: 1.安装mysql 2.安装python pymysql包(pymysql包支持py3 跟mysqldb用法差不多) 一.安装mysql mysql下载地址:h ...
- python下的MySQLdb使用
下载安装MySQLdb <1>linux版本 http://sourceforge.net/projects/mysql-python/ 下载,在安装是要先安装setuptools,然后在 ...
- python在windows下连接mysql数据库
一,安装MySQL-python python 连接mysql数据库需要 Python interface to Mysql包,包名为 MySQL-python ,PyPI上现在到了1.2.5版本.M ...
随机推荐
- Maven学习总结
转载至:http://www.cnblogs.com/xdp-gacl/p/3498271.html 一 入门 一.Maven的基本概念 Maven(翻译为"专家","内 ...
- sharepoint2013隐藏左侧导航栏更换新的
$("#zz16_V4QuickLaunchMenu").hide()//隐藏 更换新的 <script type="text/javascript" s ...
- android studio Error:java.lang.OutOfMemoryError: GC overhead limit exceeded
android studio Error:java.lang.OutOfMemoryError: GC overhead limit exceeded 在app下的build.gradle中找到and ...
- FastReport报表对象介绍一:“Text”对象
FastReport中文网 http://www.fastreportcn.com/Article/70.html ------------------------------------------ ...
- Windows下安装node
1.安装node及npm Windows下安装软件都是傻瓜式安装,首先登陆官网(https://nodejs.org/en/)下载对应的node程序,然后双击进行安装.安装过程基本上是点击'Next' ...
- Python~list,tuple^_^dict,set
tuple~(小括号) list~[中括号] 和list比较,dict有以下几个特点: dict~{‘key’:value,} set~set([1,2,3]) tuple一旦初始化就不能修改~指向不 ...
- pgbouncer介绍
一.Pgbouncer 的介绍 Pgbouncer是一个针对PostgreSQL数据库的轻量级连接池,任何目标应用都可以把 pgbouncer 当作一个 PostgreSQL 服务器来连接,然后pgb ...
- [转]finished with non-zero exit value 2
Error:Execution failed for task ':phoneacompany:dexDebug'. > com.android.ide.common.process.Proce ...
- Mysql 基础2
创建数据库: create database/*条件*/+ text3/*数据库名称*/ 创建数据库 步骤:查询 创建查询 查询编辑器 (写代码) 删除数据库: drop datab ...
- supersr--class_copyIvarList和class_copyPropertyList的区别
class_copyPropertyList返回的仅仅是对象类的属性(@property申明的属性), 而class_copyIvarList返回类的所有属性和变量(包括在@interface大括号中 ...