Python实现对Mysql数据库的增删改查

客户需求
使用Python脚本实现对对Mysql数据库的增删改查

import pymysql

# 显示
def readTable(cursor):
    # 选择全部
    cursor.execute("select * from premoney")
    # 获得返回值,返回多条记录,若没有结果则返回()
    results = cursor.fetchall()

    # 遍历打印
    for row in results:
        salesman = row[0]
        shool = row[1]
        admoney = row[2]
        print(salesman, shool,admoney, '\n')

    print("successfully show table")

# 插入
def insertData(db, cursor):
    # 插入数据
    sql = """INSERT INTO premoney (salesman, shool, admoney)VALUES
                  (1, '北京', 18),
                  (2, '上海', 18);"""
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()

        print("successfully insert data")
    except:
        # 发生错误时回滚
        db.rollback()

# 查找
def findRecord(cursor, key, value):
    # 要执行的sql语句
    sql = "select * from premoney where " + key + "=" + value
    cursor.execute(sql)
    result = cursor.fetchall()
    print("successfully find")

# 删除
def deleteRecord(db, cursor, key, value):
    # 要执行的sql语句
    sql = "delete from premoney where " + key + "=" + value
    cursor.execute(sql)
    db.commit()
    print("successfully delete")

# 更改
def updateRecord(db, cursor, key,value):
    # 要执行的sql语句
    sql = "update premoney set admoney = 20 where " + key + "=" + value
    cursor.execute(sql)
    db.commit()
    print("successfully update")



if __name__ == '__main__':
    # 链接mysql数据库
    db = pymysql.connect(host="xxx.xxx.xx.xxx",user="xxxxx", password="xxxxx",db="xxxxx",port=3307)
    # 创建指针
    cursor = db.cursor()
    # 显示表中内容
    readTable(cursor)
    # 插入数据
    insertData(db, cursor)
    # 查找数据
    findRecord(cursor, "shool", "'北京'")
    # 删除数据
    deleteRecord(db, cursor, "salesman", "'2'")
    # 更改数据
    updateRecord(db, cursor, "salesman", "'文艺'")
    # 显示表中内容
    readTable(cursor)
    # 关闭游标链接
    cursor.close()
    # 关闭数据库服务器连接,释放内存
    db.close()

你可能感兴趣的:(Python,Mysql,增删改查,Python)