我不知道为什么curs.execute无法正常工作

时间:2020-09-14 02:34:35

标签: python mysql

我正在研究与python(pycharm)的mysql连接 我对curs.execute()有疑问 它什么时候起作用,什么时候不起作用... 在我的代码中,我写了关于不工作点的评论

import pymysql

try:
    conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
    conn.set_charset('utf8')

    curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성
    # curs = conn.cursor()
    print("Connected to MySQL")

    sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"
    # sql = "select* from db_score"
    curs.execute(sql)
    #this point not work :(


except Exception as e:
    print(str(e))

finally:
    if conn:
        curs.close()
        conn.close()
        print("MySql connection is closed")

和fetchall()无效:(\

import pandas as pd
import pymysql

xl_file = 'db_score.xlsx'
df = pd.read_excel(xl_file)
tp = list(df.itertuples(index=False, name=None))

# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')

try:
    conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
    conn.set_charset('utf8')
    #curs = conn.cursor(pymysql.cursors.DictCursor)
    curs = conn.cursor()
    print("Connected to MySQL")

    sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"

    for i in range(0, len(df.index)):
        # print('hi')
        curs.execute(sql, tp[i])
    #why work i dont know because other part is not working

    # sql2 = "SELECT* from db_score"
    # curs.execute(sql2)
    # try execute, but not work

    records = curs.fetchall()

    for row in records:
        print("why didn't work")
        print(row)
    #print not work :(

    conn.commit()

except Exception as e:
    print(str(e))
    conn.rollback()

finally:
    if conn:
        curs.close()
        conn.close()
        print("MySql connection is closed")

请评论为什么工作,为什么不工作... 谢谢收看 数据库连接是如此困难:(

0 个答案:

没有答案