pymysql模块:连接mysql数据库的模块[Python基础]
pymysql模块
pymysql是一个连接mysql数据库的第三方模块,可作为连接mysql数据库的客户端,对数据库进行增删改查操作
# 下载第三方模块:pip3 install pymysql
如何连接数据库并对数据库进行操作:
# 1.连接数据库"""
需要传入的参数:
host=None,
user=None,
password="",
database=None,
port=0,
charset="",
autocommit=True # 默认提交
"""
client = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="123",
database="test",
charset="utf8", # 一定不要写utf-8
autocommit=True
)
# print(client) # 打印结果:<pymysql.connections.Connection object at 0x00000000028A8B88>
# 2.获取游标对象。游标:可以用来提交sql命令
cursor_obj = client.cursor(pymysql.cursors.DictCursor)
# 3.通过execute可以提交sql语句(增删改查都可以,可以使用try来捕获异常)
try:
# 1)查数据
sql = "select * from books"# 输入sql语句,不用写分号
# 2)插入数据
# sql = "insert into student(id, name, sex, birthday, class) values("110", "张芳", "男", "1946", "95030")" # 不用写分号
# 提交sql语句
cursor_obj.execute(sql)
# 提交后,通过cursor_obj对象.fetchall()获取所查询到的结果
data = cursor_obj.fetchall()
for i in data:
print(i)
except Exception as e:
print(e)
# 关闭游标cursor_obj.close()
# 关闭客户端连接
client.close()
执行结果(以下为我本地数据库的数据):
{"BookID": 11425, "BookTitle": "Python", "Copyright": 1984}{
"BookID": 12786, "BookTitle": "Java", "Copyright": 1934}{
"BookID": 13331, "BookTitle": "MySQL", "Copyright": 1919}{
"BookID": 14356, "BookTitle": "PHP", "Copyright": 1966}{
"BookID": 15729, "BookTitle": "PERL", "Copyright": 1932}{
"BookID": 16284, "BookTitle": "Oracle", "Copyright": 1996}
以上是 pymysql模块:连接mysql数据库的模块[Python基础] 的全部内容, 来源链接: utcz.com/z/530995.html