python -【十一】pymysql 基础使用

安装 pymysql 三方依赖
pip install pymysql

from pymysql import Connection

conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root'
)

# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')
# 使用游标对象执行 SQL 语句
cursor.execute("""
CREATE TABLE `test_pymysql` (
  `id` int NOT NULL COMMENT '主键',
  `name` varchar(255) NOT NULL COMMENT '名字',
  `age` int NOT NULL COMMENT '年龄',
  `gender` varchar(255) NOT NULL COMMENT '性别',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='pymysql测试表'
""")
# 关闭链接
conn.close()

插入/查询数据

from pymysql import Connection

conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='root',
    # 开启自动提交,无需手动 commit 事务
    autocommit=True
)


def create_data() -> str:
    data: list = []
    for i in range(1, 10):
        data.append((f'100{i}', f'张{i}', f'{20 + i}', f'{i % 2}'))

    sql: str = ''
    for datum in data:
        sql += str(datum)
        sql += ','
    return sql.rstrip(',')


# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')

print('============插入数据===========')
suffix = create_data()
all_sql = 'insert into test_pymysql values ' + suffix
print(f'插入sql:{all_sql}')
cursor.execute(all_sql)
# commit 或者是设置连接中参数:autocommit = True
# conn.commit()

print('============查询数据===========')
cursor.execute('select * from test_pymysql')
results = cursor.fetchall()  # type: tuple
for result in results:
    print(result)

# 关闭链接
conn.close()

相关推荐

  1. python -【pymysql 基础使用

    2024-06-07 21:30:02       27 阅读
  2. Python使用PyMySql增删改查Mysql数据库

    2024-06-07 21:30:02       65 阅读
  3. python------Pymysql模块

    2024-06-07 21:30:02       50 阅读
  4. PyMySQL

    2024-06-07 21:30:02       43 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 21:30:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 21:30:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 21:30:02       87 阅读
  4. Python语言-面向对象

    2024-06-07 21:30:02       96 阅读

热门阅读

  1. 二维数组知识点

    2024-06-07 21:30:02       23 阅读
  2. 大模型训练学习笔记

    2024-06-07 21:30:02       35 阅读
  3. RDMA (1)

    RDMA (1)

    2024-06-07 21:30:02      30 阅读
  4. C# using的几个用途

    2024-06-07 21:30:02       27 阅读
  5. web学习笔记(六十四)

    2024-06-07 21:30:02       26 阅读
  6. 中介子方程四

    2024-06-07 21:30:02       25 阅读
  7. 深入探索Spark MLlib:大数据时代的机器学习利器

    2024-06-07 21:30:02       29 阅读