美文网首页
Python上的Mysql的连接与操作

Python上的Mysql的连接与操作

作者: 言蹊灬 | 来源:发表于2021-01-04 18:05 被阅读0次

注意:本教程基于python3.9,不一定适用于2.x版本。
需要用到pymysql标准库
pip3 install pymysql

import pymysql.cursors

# 创建SQL连接
connect = pymysql.Connect(
    host='',
    port=3306,
    user='',
    passwd='',
    db='',
    charset='utf8'
)

# 获取游标(带字段名输出)
cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)

# 获取游标(仅输出数据)
# cursor = connect.cursor()

goodsId = ' '

# SQL文(增删改查巴拉巴拉的一些操作)
querySQL = f'SELECT id,created_at FROM product_goods_stock_bill_item where goods_id = "{goodsId}" AND deleted = false ORDER BY check_in_out_date_time ASC'

# 执行SQL文
cursor.execute(querySQL)

# 获取数据
result = cursor.fetchall()

for row in result:
    print(row)

# 关闭游标
cursor.close()
# 关闭连接
connect.close()

# 带字段名输出
{'id': 'C89YZV684LCZX5PR', 'created_at': datetime.datetime(2021, 1, 4, 9, 8, 2)}
{'id': 'C89ZFIWQEJ5K4VQE', 'created_at': datetime.datetime(2021, 1, 4, 9, 28, 29)}
{'id': 'C89ZQ5P3KW1Q4ORT', 'created_at': datetime.datetime(2021, 1, 4, 9, 42, 22)}
{'id': 'C8A1KLBNAC4TT490', 'created_at': datetime.datetime(2021, 1, 4, 11, 9, 8)}
{'id': 'C8A93R4GGIUNJGMZ', 'created_at': datetime.datetime(2021, 1, 4, 17, 3, 17)}
# 仅数据输出
('C89YZV684LCZX5PR', datetime.datetime(2021, 1, 4, 9, 8, 2))
('C89ZFIWQEJ5K4VQE', datetime.datetime(2021, 1, 4, 9, 28, 29))
('C89ZQ5P3KW1Q4ORT', datetime.datetime(2021, 1, 4, 9, 42, 22))
('C8A1KLBNAC4TT490', datetime.datetime(2021, 1, 4, 11, 9, 8))
('C8A93R4GGIUNJGMZ', datetime.datetime(2021, 1, 4, 17, 3, 17))

相关文章

网友评论

      本文标题:Python上的Mysql的连接与操作

      本文链接:https://www.haomeiwen.com/subject/ztwvoktx.html