Python编程:MySQLdb模块对数据库的基本增删改查操作
【摘要】 安装
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
Python3
https://pypi.org/project/mysqlclient/
pip install mysqlclient
使用方式和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()
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/90606464
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)