python MySQL操作(增删改查)

"""
创建一个学生表,如下:
CREATE DATABASE python_mysql_test01;
CREATE TABLE tb_student(
	stu_id INT PRIMARY KEY NOT NULL,
	stu_name VARCHAR(20) NOT NULL,
	stu_birth DATE,
	stu_addr VARCHAR(100)
);

插入一些数据:
INSERT INTO tb_student VALUES
	(1001, '张三丰', '1990-12-15', '湖北省武汉市'),
	(1002, '杨慕禅', '1998-08-09', '河南省焦作市');

最终的表如下所示:
stu_id       stu_name       stu_birth       stu_addr
1001         张三丰          1990-12-15      湖北省武汉市
1002         杨慕禅          1998-08-09      河南省焦作市

下面针对这个学生表进行增删改查的操作
"""

# 首先需要pip install pymysql
import pymysql
from pymysql import MySQLError


class PythonMysql:
    def __init__(self):
        # 连接数据库
        try:
            self.conn = pymysql.connect(host='1.1.1.1', port=3306,
                                        user='abc', password='123456',
                                        database='python_mysql_test01', charset='utf8')
        except Exception as error:
            print('连接出现问题!')
            print('失败原因:', error)
            exit()

    # 向数据库插入数据
    def insert_data(self):
        with self.conn.cursor() as cursor:
            try:
                # 插入SQL语句,result为返回的结果
                result = cursor.execute(
                    'insert into tb_student values (1004, "俞连舟", '
                    '"1999-07-29", "广东省珠海市")'
                )
                # 等于1代表1行被改变
                if result == 1:
                    print('添加成功')
                # 成功插入后需要提交才能同步在数据库中
                self.conn.commit()
            except MySQLError as error:
                print(error)
                self.conn.rollback()
            finally:
                # 操作执行完成后,需要关闭连接
                self.conn.close()

    # 删除数据库中的某一信息
    def delete_data(self):
        stu_id = input('输入需要删除的学生学号:')

        with self.conn.cursor() as cursor:
            try:
                result = cursor.execute(
                    'delete from tb_student where stu_id=%s', (stu_id,)
                )
                if result == 1:
                    print('删除成功')
                self.conn.commit()
            except MySQLError as error:
                print(error)
                self.conn.rollback()
            finally:
                self.conn.close()

    # 修改数据库中的某一记录的地址信息
    def update_data(self):
        stu_id = input('输入需要修改的学生学号:')
        stu_addr = input('输入新的地址信息:')

        with self.conn.cursor() as cursor:
            try:
                result = cursor.execute(
                    'update tb_student set stu_addr=%s where stu_id=%s', (stu_addr, stu_id,)
                )
                if result == 1:
                    print('修改成功')
                self.conn.commit()
            except MySQLError as error:
                print(error)
                self.conn.rollback()
            finally:
                self.conn.close()

    # 查询数据库中的信息
    def select_data(self):
        with self.conn.cursor() as cursor:
            cursor.execute('select stu_id, stu_name, stu_addr from tb_student')
            print('学号         姓名         家庭住址')
            for per_info in cursor.fetchall():
                for i in per_info:
                    print(i, end='\t\t')
                print()


if __name__ == '__main__':
    python_mysql = PythonMysql()

    # python_mysql.insert_data()
    # python_mysql.delete_data()
    # python_mysql.update_data()
    python_mysql.select_data()

  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楊木木8023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值