How to exec multiple queries using mysqldb on flask - python

I've been trying to make my code works but can't find why won't it does what it does.
I'm trying to put data in my database, by it only seem to exec one ....
The code is :
def setCubesValues(value):
mysql.connection.autocommit(on=True)
tabVal = value.split(';;')
del tabVal[0]
for i in range(0, len(tabVal)):
tabi = tabVal[i]
cur = mysql.connection.cursor()
responseCur = cur.execute('SELECT * FROM idcudetoaction where id_cube = "' + tabi +'"')
if responseCur == 1:
curResultInsert = cur.execute('update idcudetoaction set action = "' + tabi +'" where id_cube = ' + str(i))
else:
curResultInsert = cur.execute('insert into idcudetoaction (id_cube, action) values (' + str(i)+', "' + tabi +'")')
return jsonify(curResultInsert);
Thing is I have 7 values, but only on that get put in the database ...
Any help ? :)
thx !

Related

psycopg2 dictionary dump to json

Sorry if this is a noob question, but I am trying to dump a psycopg2 dictionary directly into a json string. I do get a return value in the browser, but it isn't formatted like most of the other json examples I see. The idea being to dump the result of a select statement into a json string and unbundle it on the other end to add into a database on the client side. The code is below and a sample of the return. Is there a better way to do this operation with json and psycopg2?
# initializing variables
location_connection = location_cursor = 0
sql_string = coordinate_return = data = ""
# opening connection and setting cursor
location_connection = psycopg2.connect("dbname='' user='' password=''")
location_cursor = location_connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
# setting sql string and executing query
sql_string = "select * from " + tablename + " where left(alphacoordinate," + str(len(coordinate)) + ") = '" + coordinate + "' order by alphacoordinate;"
location_cursor.execute(sql_string)
data = json.dumps(location_cursor.fetchall())
# closing database connection
location_connection.close()
# returning coordinate string
return data
sample return
"[{\"alphacoordinate\": \"nmaan-001-01\", \"xcoordinate\":
3072951151886, \"planetarydiameter\": 288499, \"planetarymass\":
2.020936938e+27, \"planetarydescription\": \"PCCGQAAA\", \"planetarydescriptionsecondary\": 0, \"moons\": 1"\"}]"
You could create the JSON string directly in Postgres using row_to_json:
# setting sql string and executing query
sql_string = "select row_to_json(" + tablename + ") from " + tablename + " where left(alphacoordinate," + str(len(coordinate)) + ") = '" + coordinate + "' order by alphacoordinate;"
location_cursor.execute(sql_string)
data = location_cursor.fetchall()

Why Sqlite3 table wont UPDATE

I've tried making an update to my sqlite3 table but it doesn't seem to work.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()
I can't see nay error in my code.
You don't need 4 separate statements.
You can do it in 1 statement with CASE expressions:
UPDATE tablename
SET ENG = CASE WHEN ENG = 'nan' THEN -1 ELSE ENG END,
KIS = CASE WHEN KIS = 'nan' THEN -1 ELSE KIS END,
MAT = CASE WHEN MAT = 'nan' THEN -1 ELSE MAT END,
BIO = CASE WHEN BIO = 'nan' THEN -1 ELSE BIO END
WHERE 'nan' IN (ENG,KIS,MAT,BIO)
This worked, separating them.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) + "' SET ENG=-1 WHERE ENG='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET KIS=-1 WHERE KIS='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET MAT=-1 WHERE MAT='nan'")
cur.execute("UPDATE '" + str(marks) + "' SET BIO=-1 WHERE BIO='nan'")
conn.commit()
conn.close()
Rather than this.
marks = "My long name here"
conn = sqlite3.connect('mydb.db')
cur=conn.cursor()
cur.execute("UPDATE '" + str(marks) +"' SET (ENG,KIS,MAT,BIO) = (-1,-1,-1,-1) WHERE (ENG,KIS,MAT,BIO) =('nan','nan','nan','nan')")
conn.commit()
conn.close()

Why Does Empty MySQL Database Claim to Have Duplicates (Python 3)?

So I have a quick function that's supposed to upload data (stored in a Python dictionary) to a MySQL database.
def uploadData(of_item):
global DB_HOST
global DB_USER
global DB_PASSWORD
global DB_DATABASE
my_db = connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASSWORD, database=DB_DATABASE, port=3306)
my_db.autocommit = True
my_cursor = my_db.cursor()
print("\rThe DB pipeline is now connected.")
slots_text = ", ".join([a[0] for a in of_item.items()])
values_text = ", ".join(["'" + a[1].replace("'", "\\'") + "'" for a in of_item.items()])
set_portion_text = ", ".join([a[0] + " = " + "'" + a[1].replace("'", "\\'") + "'" for a in of_item.items()])
sql = 'INSERT INTO UsersData ({0}) VALUES ({1})'.format(slots_text, values_text)
try:
my_cursor.execute(sql)
row_cnt = my_cursor.rowcount
my_db.commit()
my_cursor.close()
my_db.close()
print("\r" + str(row_cnt) + " is now in UsersData.")
return [True, str(row_cnt)]
except Exception as exception:
print("\n".join(["The update failed for profileID: " + of_item['UniqueId'],
str(exception),
str(sql),
"*",
'Item:',
str(of_item),
"*"]))
my_cursor.close()
my_db.close()
return [False, 0]
Currently, the row_cnt sits at -1, so it should be entirely empty. However, when I execute the function, I'm constantly getting this thrown error:
1062 (23000): Duplicate entry 'ABCDEFGHIJKLMNOPQRSTUVWXYZ-123' for key 'profileId_2'
Now, profileId_2 is just this:
...
UNIQUE KEY `profileId_2` (`profileId`,`companyId`),
...
profileId is whatever the user's unique ID is, and companyId is just a preset (in this case, 123). It's odd that there would be a claimed duplicate, since there's nothing in the database yet.
First, what might be causing this error? Second, how can I get through it and successfully append new entries to UsersData?

Select Column from Table in Django Not Working

I am trying to access the two specific column from the table in Django it is not Working but When I am trying to access select * it is working
I am using postgresql
When I am trying to access select all its working this is I am trying to access for particular column
def bigdataDatabase(X):
engine = sqlalchemy.create_engine('postgresql+psycopg2://postgres:password#localhost/db_name')
con = engine.connect()
result = con.execute(
"Select Orign,Departure From 'table_name' WHERE index = '" + str(X) + "'")
This is not working
I have also tried with this
result = con.execute("Select tablename.Orign,tablename.departure From 'table_name' WHERE index = '" + str(X) + "'")
both the above code is not working
Programming Error column does not exist
But When I am executing all this it is working
result = con.execute("Select * From 'table_name' WHERE index = '" + str(X) + "'")
I have found the solution of the problem the query should be executed like this
result = con.execute('Select "Orign","Departure" From "Table_name" WHERE index = ' + str(X))

python 3.5 selecting and using results from postgres database

I need to write a program which can,firstly, for ip adresses of people who saw my campaign on google, and then give me detailed information about each of these persons.
I have all information in postgres database and use python 3.5
Here is my code:
def get_connection(cursor_factory=None):
conn_string_pg = "host= '" + host + "' dbname = '" + dbname + "' user = '" + user + \
"' password = '" + password + "'"
if cursor_factory is None:
conn_pg = psycopg2.connect(conn_string_pg)
else:
conn_pg = psycopg2.connect(conn_string_pg,
cursor_factory=cursor_factory)
return conn_pg
def find_logs():
select = """ select ip_address from log_files o where o.url like
'%my_campaign'
"""
conn = get_connection(cursor_factory = RealDictCursor)
cur = conn.cursor()
cur.execute(select)
records = cur.fetchone()
for item in records:
select_2 = "select * from log_files where ip_address = %(item)s "
cur.execute(select_2)
logs = cur.fetchone()
return logs
print(find_logs())
cur.close()
Unfortunately I get this error:
psycopg2.ProgrammingError: syntax error at or near "%" LINE 1:
...elect * from web_logs.log_data where ip_address = %(item)s o...
Your string interpolation is incorrect. You're trying to insert the value of item into your select_2 statement, but you don't actually do the string interpolation, so you pass psycopg2 an invalid SQL statement. You want to do something like
select_2 = "select * from log_files where ip_address = {}".format(item)
It's because ip_address = %(item)s it's not a valid sql syntax. You should make string formatting before:
select_2 = "select * from log_files where ip_address = %(item)s " % {'item': item}
And the better way to do it is to give all the transformation to the postgres driver
select_2 = "select * from log_files where ip_address = %s "
cur.execute(select_2, (item, ))

Categories