• python 操作MySQL


    mysql 表数据

    Python安装pymysql:pip install PyMySQL

     1 import pymysql
     2 # 打开数据库连接
     3 connect = pymysql.Connect(
     4     host='localhost',
     5     port=3306,
     6     user='root',
     7     passwd='123456',
     8     db='test',
     9     charset='utf8'
    10 )
    11 
    12 # 使用cursor()方法获取操作游标
    13 cur = connect.cursor()
    14 # 增加
    15 sql = "INSERT INTO student VALUES ('%s','%s','%s','%s')" % (6, "李思思", 9, "")
    16 try:
    17     cur.execute(sql)
    18     connect.commit()
    19 except:
    20     connect.rollback()
    21 
    22 # 查询
    23 sql = "SELECT * FROM student"
    24 cur.execute(sql)
    25 # 获取所有记录列表
    26 result = cur.fetchall()
    27 for row in result:
    28     Sn0 = row[0]
    29     Sname = row[1]
    30     Sage = row[2]
    31     Ssex = row[3]
    32     print("Sno=%s,Sname=%s,Sage=%s,Ssex=%s" % (Sn0, Sname, Sage, Ssex))
    33 
    34 # 删除
    35 sql = "DELETE FROM student WHERE Sno='%s'" % 6
    36 try:
    37     cur.execute(sql)
    38 
    39     # 提交到数据库执行
    40     connect.commit()
    41 except:
    42     # 发生错误时回滚
    43     connect.rollback()
    44 
    45 sql = "SELECT * FROM student"
    46 cur.execute(sql)
    47 result = cur.fetchall()
    48 for row in result:
    49     Sn0 = row[0]
    50     Sname = row[1]
    51     Sage = row[2]
    52     Ssex = row[3]
    53     print("Sno=%s,Sname=%s,Sage=%s,Ssex=%s" % (Sn0, Sname, Sage, Ssex))
    54 
    55 # 更新
    56 sql = "UPDATE student SET Sage = '%s' WHERE Sno = '%s'" % (19,4)
    57 try:
    58     cur.execute(sql)
    59 
    60     # 提交到数据库执行
    61     connect.commit()
    62 except:
    63     # 发生错误时回滚
    64     connect.rollback()
    65 
    66 sql = "SELECT * FROM student"
    67 cur.execute(sql)
    68 result = cur.fetchall()
    69 for row in result:
    70     Sn0 = row[0]
    71     Sname = row[1]
    72     Sage = row[2]
    73     Ssex = row[3]
    74     print("Sno=%s,Sname=%s,Sage=%s,Ssex=%s" % (Sn0, Sname, Sage, Ssex))
    75 # 关闭数据库连接
    76 connect.close()
  • 相关阅读:
    C++11新特性
    Qt操作xml
    指针和引用的区别
    QT软件主题切换
    常见的临时变量的生成场景
    QQuickWidget+QML设置背景透明
    idea maven Could not transfer artifact
    Java项目启动时执行指定方法的几种方式
    解决bootstrap-table在切换分页后再次查询报错404问题
    bootstrap:表单必填项*标识,及提交前校验
  • 原文地址:https://www.cnblogs.com/jescs/p/8144811.html
Copyright © 2020-2023  润新知