栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

pymysql,创建连接对象,获取游标,建立连接执行sql语句,提交到数据库,对修改数据进行撤销回滚关闭游标,关闭连接

pymysql,创建连接对象,获取游标,建立连接执行sql语句,提交到数据库,对修改数据进行撤销回滚关闭游标,关闭连接

1.导包
2.创建连接对象
3.获取游标,目的是要执行sql语句
4.执行sql语句
5.关闭游标
6.关闭连接

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import pymysql

#建立连接(客户端连接服务端)
conn = pymysql.connect(
    host='',
    port=3306,
    user='root',
    password='',
    database='',
    charset='utf8'  #不带-
)



#游标
cursor = conn.cursor(pymysql.cursors.DictCursor)
#默认游标取出来的数据是元组((),)
#DictCursor对应的数据结构{[],],如果用的是fetcheone,那么结果是{}
sql = "insert into digital_image values(13,"pumysql001");"

try:
    ret = cursor.execute(sql)
    print(ret)
    # 增删改都必须进行提交操作(commit)
    conn.commit(sql)
except  Exception as e:
    #对插入、修改、删除的数据进行撤销,表示数据回滚(回到没有修改数据之前的状态)
    conn.rellback
finally:
    #关闭游标
    cursor.close()
    #关闭连接
    conn.close()

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

查询的sql语句,则不需要提交,不用执行commit,conn.commit(sql)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283152.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号