搜索
首页数据库mysql教程快速熟悉python 下使用mysql(MySQLdb)

python

首先你需要安装上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执行各种操作了,示例代码如下:

1 import MySQLdb2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)3 cur=cxn.cursor()4 result=cur.execute('select * from students')5 for i in cur.fetchall():6 print i

这段代码就能返回表students中的所有信息了,也就是你进入mysql输入select * from students之后所显示的内容。这里我就假设大家都了解sql的语句 使用了(不了解的可以去学或者用ORM操作数据库)

接下来我们演示一下怎么更新表,以怎么向表中插入数据为例:

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 cur.execute("insert into students values(4,'liu4',100)")10 print 'after insert'11 showtables('students')

这样我们会可以看待结果:

(1L, 'liu', Decimal('100'))(2L, 'liu2', Decimal('90'))(3L, 'liu3', Decimal('98'))after insert(1L, 'liu', Decimal('100'))(2L, 'liu2', Decimal('90'))(3L, 'liu3', Decimal('98'))(4L, 'liu4', Decimal('100'))

看似是一摸一样的完成了这项工作,但是这时候我们用终端连上mysql。执行一条select * from students却发现我们插入的那条并没有进去。这是因为 我们还缺少一个commit工作。另外工作完成之后我们需要关闭与数据库的连接,于是更改代码如下

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 cur.execute("insert into students values(4,'liu4',100)")10 cxn.commit()11 print 'after insert'12 showtables('students')13 cur.close()14 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结合起来,这样我们就可以批量操做了

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 v=[]10 for i in range(10):11 v.append((i,'liu'+str(i),98))12 cur.executemany("insert into students values(%s,%s,%s)",v)13 cxn.commit()14 print 'after insert'15 showtables('students')16 cur.close()17 cxn.close()

上面用到了两处参数,第五行和第12行

另外当执行多个命令要用executemany(op,args)它类似 execute() 和 map() 的结合, 为给定的每一个参数准备并执行一个数据库查询/命令

五、零碎

上面说过db这个属性可以在连接之后指定,如下:

cxn.select_db('students')
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存储斑点安全吗?mysql:存储斑点安全吗?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通过PHP Web界面添加用户mySQL:通过PHP Web界面添加用户May 14, 2025 am 12:04 AM

通过PHP网页界面添加MySQL用户可以使用MySQLi扩展。步骤如下:1.连接MySQL数据库,使用MySQLi扩展。2.创建用户,使用CREATEUSER语句,并使用PASSWORD()函数加密密码。3.防止SQL注入,使用mysqli_real_escape_string()函数处理用户输入。4.为新用户分配权限,使用GRANT语句。

mysql:blob和其他无-SQL存储,有什么区别?mysql:blob和其他无-SQL存储,有什么区别?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而alenosqloptionslikemongodb,redis和calablesolutionsoluntionsoluntionsoluntionsolundortionsolunsolunsstructureddata.blobobobsimplobissimplobisslowderperformandperformanceperformancewithlararengelitiate;

mySQL添加用户:语法,选项和安全性最佳实践mySQL添加用户:语法,选项和安全性最佳实践May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串数据类型常见错误?MySQL:如何避免字符串数据类型常见错误?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingsefectery.1)usecharforfixed lengengters lengengtings,varchar forbariaible lengength,varchariable length,andtext/blobforlabforlargerdata.2 seterters seterters seterters seterters

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!