Insert from python to mysql

Question:

How to insert data from code below?
I have a code below

latitude1 = -6.208470935786019
longitude1 = 106.81796891087399
new_data = [[latitude1, longitude1]]
preds = model.predict(new_data)
preds

arr = [latitude1,longitude1]
arrcon = np.concatenate((arr,preds))
print(arrcon) #[-6.208470935786019 106.81796891087399 'Not Categorized']

listarcon= arrcon.tolist()
print(listarcon) #[-6.208470935786019, 106.81796891087399, 'Not Categorized']

#make the list into multi list
singlearcon = np.array(listarcon).reshape(1,3)
print(singlearcon) #[['-6.208470935786019' '106.81796891087399' 'Not Categorized']]

This is insert into database code

mycursor = conn.cursor()
sql = "INSERT INTO traveldata (Latitude,Longitude,Wisata) VALUES (%s, %s, %s)"
val = (listarcon[0],listarcon[1],listarcon[2])
mycursor.execute(sql, val)

example

How to insert it to database? the data didn’t seem to get to the database.

Asked By: Jessen Jie

||

Answers:

After executing a transaction mycursor.execute(sql, val), we should commit the change mycursor.commit()

Reference for the commit method https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-commit.html

An example of insert code https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.