python数据库如何学习_PyThon教程:MySQL数据库学习如何处理

d57a89aa9e174ec57397d9d6eadf123a.png

在学习python过程中,熟练掌握数据库使用是非常重要的,python对接多种数据库,如:GadFly、mSQL、MySQL、PostgreSQL等等,想要了解访问MySQL数据库,可以看下面使用流程:

一、链接数据库conn = pymysql.connect(host='127.0.0.1', port=3306, user='school_spt', passwd='123456', db='school_info')   #返回个链接对象

二、创建游标cursor = conn.cursor()

三、sql拼接命令

1.字符串拼接(不推荐使用该方式,容易被sql注入)user='root'

pwd='123456'

sql='select * from userinfo where password=%s and username=%s'%(pwd,user)

2.pymysql命令自带拼接executsql命令, args)    #args可以是列表,元组或者字典

列表:

user='root'

pwd='123456'

sql='select * from userinfo where password=%s and username=%s'

cursor.execute(sql,[pwd,user])

元组

user='root'

pwd='123456'

sql='select * from userinfo where password=%s and username=%s'

cursor.execute(sql,(pwd,user))

字典

sql='select * from userinfo where password=%(password)s and username=%(username)s'

cursor.execute(sql,({'password':pwd,'username':user}))

四、查sql='select * from userinfo'

res=cursor.execute(sql)   #返回受影响的行数

#获取返回的数据

cursor.fetchone()      #获取返回的第一行内容

cursor.fetchmany(n)    #获取返回的前n行内容

cursor.fetchall()          #获取返回的全部内容

#返回的数据默认是元组形式,如果要以字典形式显示

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

五、改(改,删,增)

1.增sql=‘insert into userinfo(username,password) values(%s,%s)’

cursor.execute(sql,('root','123'));   #单条插入

也可以使用批量插入数据

cursor.executemany(sql,[('root','123'),('root1','1234'),('root2','123')]);

2.改,删没有批量执行命令,批量一般都使用单条执行

3.增,删,改操作后,都需要使用 conn.commit()来确认提交数据

六、execute会返回受影响的行数。一般不适用

七、scroll 在fetch数据时按照顺序进行(类似生成器),可以使用cursor.scroll(num,mode)来移动游标位置,如:cursor.scroll(1,mode='relative')  # 相对当前位置移动

cursor.scroll(2,mode='absolute') # 相对绝对位置移动

八、获取最后的自增id值(lastrowid)id=cursor.lastrowid

九、关闭游标和链接cursor.close()  #先关闭游标

conn.close()    #再关闭连接

MySQL 是一种关联数据库管理系统,关联数据库将数据保存在不同的表中,能够增加速度并提高灵活性,是很广泛的适应于日常工作的,大家可以尝试学习下啊~

更多python实用知识,点击进入云海天Python教程网。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值