Python编程:MySQLdb模块对数据库的基本增删改查操作

举报
彭世瑜 发表于 2021/08/14 00:44:01 2021/08/14
【摘要】 安装 Python2 https://pypi.org/project/MySQL-python/ pip install MySQL-python 1 Python3 https://pypi.org/project/mysqlclient/ pip install mysqlclient 1 使用方式和PyMySQL 类似,如果有条件还是优先使用 PyMy...

安装

Python2
https://pypi.org/project/MySQL-python/

pip install MySQL-python

  
 
  • 1

Python3
https://pypi.org/project/mysqlclient/

pip install mysqlclient

  
 
  • 1

使用方式和PyMySQL 类似,如果有条件还是优先使用 PyMySQL :
可参考:SQL:pymysql模块读写mysql数据

代码示例

# -*- coding: utf-8 -*-

import MySQLdb

con_config = { "host": "127.0.0.1", "port": 3306, "user": "root", "password": "123456", "database": "demo", "autocommit": True  # 不提交修改不生效,3中方式任选一种
}

# autocommit = True # 提交1:连接的时候就开启自动提交
# con.autocommit(True)  # 提交2:执行SQL语句之前设置自动提交
# con.commit() # 提交3:执行SQL语句之后提交


# 连接数据库,获得游标
con = MySQLdb.connect(**con_config)
cursor = con.cursor()


# 1、插入单条数据
insert_sql = "insert into student(name, age) values(%s, %s)"
cursor.execute(insert_sql, ("Tom", 23))
print(cursor.rowcount)
# 1


# 2、插入多条数据
# 可用于改操作: insert, delete, update
cursor.executemany(insert_sql, [("Jack", 24), ("Jimi", 25)])
print(cursor.rowcount)  # 无论提交还是不提交,rowcount都有数据,不要被误导
# 2


# 3、删除数据
delete_sql = "delete from student where id=%s"
cursor.execute(delete_sql, (1,))  # 第二个参数为一个可迭代对象,只有一个参数要传元组
print(cursor.rowcount)
# 1


# 4、修改数据
update_sql = "update student set age=99 where id=%s"
cursor.execute(update_sql, (4,))
print(cursor.rowcount)
# 1


# 5、查询单条  查询不需要提交
select_sql = "select name, age from student limit %s"
cursor.execute(select_sql, (1,))
row = cursor.fetchone()
print(row)
# ('Tom', 99)


# 6、查询多条数据
cursor.execute(select_sql, (2,))
rows = cursor.fetchall()
print(rows)
# (('Tom', 23), ('Tom', 23))


# 关闭游标和数据库连接
cursor.close()
con.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
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。

原文链接:pengshiyu.blog.csdn.net/article/details/90606464

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。