• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞java代码 3年前 (2022-05-15) 14次浏览 已收录 0个评论

在学习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')   #返回个链接对象

www#gaodaima.com来源gao($daima.com搞@代@#码网搞代码

二、创建游标

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教程网

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PyThon教程:MySQL数据库学习如何处理
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址