Python 之PyMysql

随笔7天前发布 刘建闯
22 0 0

合集 – Python(7)
1.Pycharm使用之心得2020-06-282.Python 之pip换源09-053.Python 之线程池09-044.Python 之数据库操作09-045.Python 之SQLAlchemy09-05
6.Python 之PyMysql09-107.Python 之records教程09-13

收起

Python 之PyMysql

目录Python 之PyMysqlPymysql教程使用教程

Pymysql教程#

介绍:

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库

安装

pip install PyMySQL

使用教程#

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#    @Author :Alex
#
#              _____               ______
#     ____====  ]OO|_n_n__][.      |    |]
#    [________]_|__|________)<     
#     oo    oo  'oo OOOO-| oo\_   ~o~~~o~'
# +--+--+--+--+--+--+--+--+--+--+--+--+--+
#    @Time : 2024/9/10 15:18
#    @FIle: do_pymyql.py
#    @Software: PyCharm

# 打开数据库连接
db = pymysql.connect(host='127.0.0.1', port=3306, database='test', user='root', password='mysql_EEnSPA')
# 设置事务自动提交
db.autocommit(True)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 执行一条 SQL 查询语句
cursor.execute("SELECT VERSION()")
# 获取一条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 创建表
create_table_sql = """
CREATE TABLE `test` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=armscii8;
"""
cursor.execute(create_table_sql)
# 表中插入数据 和数据修改都一样
insert_sql = "insert into test(name) values( %s)"
insert_data = ("alex")
cursor.execute(insert_sql, insert_data)
# 批量插入多条数据,插入与修改数据都一样
insert_more_data_sql = "insert into test(name) values(%s)"
insert_more_data_list = [("alex2"), ("alex3")]
cursor.executemany(insert_more_data_sql, insert_more_data_list)

# 查询数据
cursor.execute("select * from test")
result = cursor.fetchall()
print(result)
db.close()

参考教程:https://www.runoob.com/python3/python3-mysql.html

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...