• 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()
  • 相关阅读:
    Node.js 事件驱动编程
    css常见布局
    The Perfect Solution To Convert Immutable Bitmap To A Mutable Bitmap
    Mac终端Terminal使用
    入门Mac快捷键详细分类整理,包括Eclipse和Android Studio中一些常用的快捷键
    Android自定义控件属性的使用
    Visual Studio的快捷键
    cmd中编译和运行java程序
    查看本机的IP、MAC地址和端口占用情况
    ASC2码
  • 原文地址:https://www.cnblogs.com/jescs/p/8144811.html
Copyright © 2020-2023  润新知