Python连接mysql数据库

  1. 查询
import pymysql

if __name__ == '__main__':

    # 创建连接对象
    con = pymysql.connect(host="localhost",
                          port=3306,
                          user="xxxx",
                          password="xxxx",
                          database="db1",
                          charset="utf8")

    # 获取游标
    cur = con.cursor()

    # sql 语句
    sql = 'select * from student;'

    # 执行
    cur.execute(sql)

    # 输出
    row = cur.fetchall()
    for i in row:
        print(i)
    # 关闭游标
    cur.close()
    con.close()
  1. 增删改
import pymysql

if __name__ == '__main__':
    con = pymysql.connect(host='localhost',
                          port=3306,
                          user='xxxx',
                          password='xxxx',
                          database='db1',
                          charset='utf8')

    cur = con.cursor()
    # sql = "insert into course values(2,'c++');"
    # sql = "update course set name='c' where id = 2;"
    sql = "delete from course where id = 2;"
    try:
        cur.execute(sql)
        # 正确提交
        con.commit()
    except Exception as e:
        # 出错回滚
        con.rollback()
    finally:
        cur.close()
        con.close()

# 在执行数据库的增删改时需要进行提交或者回滚,否则不能增删改,查询就不用

posted @ 2021-03-10 16:54  code-G  阅读(76)  评论(0编辑  收藏  举报