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()
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值