Python connect to mysql database and method of operating database

import pymysql

conn = pymysql.connect(  #连接数据库
    host = "127.0.0.1",
    port = 3306,
    user = "root",
    passwd = "gloryroad",
    db= "gloryroad",
    charset = "utf8"
    )

conn.autocommit(1)  #设置自动提交功能
cursor = conn.cursor()  #获取数据库的操作游标

try:
    cursor.execute('select * from students;')  #执行sql语句
    while 1:
        res = cursor.fetchone()  #逐条读取游标里的数据,fetchmany(2)读取指定条数的数据,fetchall()一次读取所有数据
        if res is None:
            break
        print(res)
    cursor.close()  #关闭游标
    conn.close()  #关闭连接
except pymysql.Error as e:
    print('数据库连接失败:',e)

Guess you like

Origin blog.csdn.net/weixin_44123630/article/details/114791249