Python 之PyMysql

Python 之PyMysql

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

posted @ 2024-09-10 15:36  快乐小王子帅气哥哥  阅读(424)  评论(0)    收藏  举报

Loading