尝试提交到数据库时出现“'Cursor'对象没有属性'commit'”错误

时间:2019-03-04 17:46:59

标签: python mysql

我正在致电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()

1 个答案:

答案 0 :(得分: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