Insert from python to mysql - python

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)
How to insert it to database? the data didn't seem to get to the database.

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

Related

Error when updating a database table with pymssql and a python dictionary

I am trying to write data in a dictionary back into a SQL Server database table with pymssql.
But I am getting this error:
ValueError: more placeholders in sql than params available
Here is my code:
cursor = conn.cursor()
for key in dictW:
x = dictW[key]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.executemany(sql, (key, x))
conn.commit()
conn.close()
What am I doing wrong here?
You are attempting to execute your queries one by one but are using executemany(). You should consider using a simple execute() instead:
cursor = conn.cursor()
for key in dictW:
x = dictW[key]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.execute(sql, (key, x))
conn.commit()
conn.close()
If you want to use executemany(), you should make a list of tuples like this:
cursor = conn.cursor()
params = [(k, v) for k, v in dictW.items()]
sql = 'UPDATE tablename SET col = %s WHERE %s = #url '
cursor.executemany(sql, params)
conn.commit()
conn.close()

importing values of a python dictionary as data to an existing mysql table

I have problem with storing values of a python dictionary as data to an existing mysql table
I tried to use the code below but it's not working.
db = mysql.connect(
host="localhost",
user="root",
passwd="123456",
database="tgdb"
)
cursor = db.cursor()
val = ', '.join("'" + str(x) + "'" for x in dict.values())
sql = "INSERT INTO tgdb.channel(user_name, image_url, name,
number_of_members, description, channel_url) VALUES (%s, %s, %s, %s, %s,
%s)"
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, "record inserted.")
"you have an error in your SQL syntax"
As writed #Torxed shouldn't translate dict in string, you can write just that:
cursor.execute(sql, list(dict.values())

retrieve the data from MySQL database, in dictionary format in python

import MySQLdb
def Network():
dict = {'CISCO' : 'NEXUS', 'JUNIPER' : 'JUNO', 'Alcatel' : 'Alc' }
#len(dict)
return (dict)
def db_store(variable):
con = MySQLdb.connect("localhost","root","root","fs_company" )
cur = con.cursor()
for key,value in variable.items():
cur.execute('''INSERT into google (name, company) values (%s, %s)''', (key, value))
con.commit()
cur.execute("""SELECT * FROM google""")
variable = cur.fetchall()
#print variable
variable = Network()
db_store(variable)
I have above code to store the data to mysql database, I want to retrieve the data from database in dictionary format. need help for the same
You are missing only one line. You can convert variable into dict like this:
cur.execute("""SELECT * FROM google""")
out = cur.fetchall()
variable = {key:val for key,val in out}
print(variable)

Inserting list items into database as separate entries

I have an input field that is basically a comma delimited string (i.e. something like "deniscm, toms, peters"). That information is sent via AJAX to my Python handler SaveQueryPage. What I want to do is parse this information as a list and then insert each entry into my database. My code is as follows, but it doesn't work unfortunately. Any suggestions?
Python code:
class SaveQueryPage(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
user_nickname = user.nickname()
query_name = self.request.get('queryName')
query_collab = self.request.get('queryCollab')
query_collaborators = re.split(r'\s*[,]\s*', query_collab.strip())
query_collaborators = query_collaborators.append(user_nickname)
query_collaborators = filter(None, query_collaborators)
conn = rdbms.connect(instance=_INSTANCE_NAME, database='queryInfo')
cursor = conn.cursor()
cursor.execute('INSERT INTO queries (userNickname, queryName) VALUES (%s, %s)', (user_nickname, query_name))
conn.commit()
for item in query_collaborators:
cursor = conn.cursor()
cursor.execute('INSERT INTO collaborators (queryName, userNickname) VALUES (%s, %s)', (query_name, item))
conn.commit()
conn.close()
I finally managed to get it working. Looks like the regular expression turned the items in the list to a unicode format, which was only caught when I added some logs. I also had an error in appending a string to the list. Thanks for the pointers! The code below now works for me:
class SaveQueryPage(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
user_nickname = user.nickname()
user_email = user.email()
query_name = self.request.get('queryName')
query_description = self.request.get('queryDescription')
query_collab = self.request.get('queryCollab')
logging.info('Data read for query_collab is %s', query_collab)
query_collab_re = re.split(r'\s*[,;]\s*', query_collab.strip())
logging.info('Data read for query_collab_re is %s', query_collab_re)
query_collab_decode = []
for item in query_collab_re:
item = str(item)
query_collab_decode.append(item)
logging.info('Data read for query_collab_decode is %s', query_collab_decode)
query_collab_decode.append(user_nickname)
logging.info('Data read for query_collab_append is %s', query_collab_decode)
query_collab_filter = filter(None, query_collab_decode)
logging.info('Data read for query_collab_filter is %s', query_collab_filter)
query_value = self.request.get('queryValue') # query_value
date_created = datetime.today()
date_lastupdated = datetime.today()
active_flag = "true"
random_id = random.randint(1000000000000, 9999999999999)
unique_query_id = user_nickname + "_" + str(random_id)
conn = rdbms.connect(instance=_INSTANCE_NAME, database='userPrefs')
cursor = conn.cursor()
cursor.execute('INSERT INTO queries (userNickname, queryName, queryDescription, queryValue, dateCreated, dateLastUpdated, activeFlag, uniqueId) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', (user_nickname, query_name, query_description, query_value, date_created, date_lastupdated, active_flag, unique_query_id))
conn.commit()
try:
for item in query_collab_filter:
cursor = conn.cursor()
cursor.execute('INSERT INTO collaborators (uniqueId, userNickname) VALUES (%s, %s)', (unique_query_id, item))
conn.commit()
except:
logging.error('There was an error inserting the values into the collaborators table. query_collaborators =' + str(query_collaborators))
conn.close()

Using INSERT with a PostgreSQL Database using Python

I am trying to insert data into a PostgreSQL database table using Python. I don't see any syntax errors but, for some reason, my data isn't getting inserted into the database.
conn = psycopg2.connect(connection)
cursor = conn.cursor()
items = pickle.load(open(pickle_file,"rb"))
for item in items:
city = item[0]
price = item[1]
info = item[2]
query = "INSERT INTO items (info, city, price) VALUES (%s, %s, %s);"
data = (info, city, price)
cursor.execute(query, data)
You have to commit the transaction.
conn.commit()
If there's no reason to think the transaction will fail, it's faster to commit after the for loop finishes.

Categories

Resources