“'Cursor'对象在尝试提交数据库时没有属性'commit'”错误[duplicate]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我打电话给cursor.commit,但它给了我错误'Cursor' object has no attribute 'commit'

app = Flask(__name__)
mysql = MySQL()

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'backprop_skripsi'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)  

def bacacsv(lokasiFile):
    no_baris = 0
    data = []
    with open(lokasiFile) as filecsv:
        csv_reader = csv.reader(filecsv, delimiter = ',')
        for baris in csv_reader:
            if no_baris < 1:
                no_baris += 1
            else:
                bulan = baris[0]
                rumah_tangga = baris[1]
                niaga_kecil = baris[2]
                niaga_besar = baris[3]

                insert_dataset(bulan, rumah_tangga, niaga_kecil, niaga_besar)
                no_baris += 1

                app.logger.info('bulan = %s | rumah_tangga = %s', bulan, rumah_tangga)


def insert_dataset(bulan, rumah_tangga, niaga_kecil, niaga_besar):
    cursor = mysql.connect().cursor()
    sql = "INSERT INTO tb_dataset(bulan, rumah_tangga, niaga_kecil, niaga_besar) VALUES ('" + bulan + "', " + rumah_tangga + ","+ niaga_kecil+", "+niaga_besar+");"
    app.logger.info("test = %s", sql)
    cursor.execute(sql)
    cursor.commit()
python mysql
1个回答
2
投票

你需要在commit返回的连接对象上调用mysql.connect,而不是在cursor对象上调用:

connection = mysql.connect()
cursor = connection.cursor()
sql = "INSERT INTO tb_dataset(bulan, rumah_tangga, niaga_kecil, niaga_besar) VALUES ('" + bulan + "', " + rumah_tangga + ","+ niaga_kecil+", "+niaga_besar+");"
app.logger.info("test = %s", sql)
cursor.execute(sql)
connection.commit()

此外,确保在完成后关闭光标和连接:

cursor.close()
connection.close()

有关详细信息,请参阅此处的教程:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

© www.soinside.com 2019 - 2024. All rights reserved.