python连接mysql数据库,并做增删查改操作

import pymysql  # 导入数据库模块

# 创建一个数据库对象,利用connect进行连接数据库
try:
    db = pymysql.connect(host='localhost',  # ip地址
                         database='demo1',  # 帐套名
                         user='root',  # 数据库账号
                         password='123456',  # 密码
                         port=3306  # 端口号
                         )
except:
    print('连接mysql数据库失败!')
else:
    # 创建一个游标对象  游标:可以执行sql语句,执行完sql语句有返回值
    cursor = db.cursor()  # 创建一个游标对象
    
    # 查询
    sql_select = 'select * from student0;'  # 创建一条查询语句
    cursor.execute(sql_select)  # 执行sql语句
    # all = cursor.fetchall()  #用变量名all来接收游标返回的所有内容
    one = cursor.fetchone()  # 用变量名one来接收游标返回的一条内容
    # print(all)
    print(one)

    #新增
    sql_insert = 'insert into student0(id,name,class) value(7,"小明",3)'  # 创建一条插入语句
    cursor.execute(sql_insert)  # 执行sql语句
    db.commit()  # 确认 修改表内容后需要做确认操作

    #修改
    sql_update = 'update student0 set name="小发" where id = 7'  #创建一条修改语句
    cursor.execute(sql_update) # 执行sql语句
    db.commit()  #确认

    #删除
    sql_delete = 'delete from student0 where id = 7' #创建一条删除语句
    cursor.execute(sql_delete) # 执行sql语句
    db.commit()  #确认

 

posted @ 2021-08-03 22:19  夏夏夏天的西瓜  阅读(242)  评论(0)    收藏  举报