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"
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用MySQLdb或者pymysql模块来连接MySQL数据库并进行增删改查操作。 1. 连接数据库 使用MySQLdb模块连接MySQL数据库可以使用以下代码: ``` import MySQLdb # 打开数据库连接 db = MySQLdb.connect(host="localhost", user="root", password="123456", database="test") # 使用cursor()方法获取操作游标 cursor = db.cursor() # 关闭数据库连接 db.close() ``` 使用pymysql模块连接MySQL数据库可以使用以下代码: ``` import pymysql # 打开数据库连接 db = pymysql.connect(host="localhost", user="root", password="123456", database="test") # 使用cursor()方法获取操作游标 cursor = db.cursor() # 关闭数据库连接 db.close() ``` 2. 插入数据 使用execute()方法执行SQL语句可以插入一条数据,如下所示: ``` # SQL插入语句 sql = "INSERT INTO students(name, age, grade) VALUES ('Tom', 18, 'A')" # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() ``` 3. 查询数据 使用execute()方法执行SQL语句可以查询数据,如下所示: ``` # SQL查询语句 sql = "SELECT * FROM students" # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: id = row[0] name = row[1] age = row[2] grade = row[3] # 打印结果 print("id=%d, name=%s, age=%d, grade=%s" % (id, name, age, grade)) ``` 4. 更新数据 使用execute()方法执行SQL语句可以更新数据,如下所示: ``` # SQL更新语句 sql = "UPDATE students SET age = age + 1 WHERE name = 'Tom'" # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() ``` 5. 删除数据 使用execute()方法执行SQL语句可以删除数据,如下所示: ``` # SQL删除语句 sql = "DELETE FROM students WHERE id = 1" # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() ``` 以上就是PythonMySQL数据库进行增删改查的基本操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值