Invalid Syntax error on try clause in Python [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
First I apologize if this is formatted poorly, I've never asked a question here before.
I'm running python 2.7.15 in a virtualenv on win10-64. I'm trying to upload some test strings to a MySQL database but I'm getting the dumbest error and I don't know how to get around it. The MySQL Python/Connector should be installed correctly. Same with the GCP SDK.
import mysql.connector
from mysql.connector import errorcode
# Config info will be moved into config file(s) after testing
# Google Proxy Connection (Proxy must be running in shell)
# C:\Users\USER\Google Drive\Summer Education\GCP
# $ cloud_sql_proxy.exe -instances="pdf2txt2sql-test"=tcp:3307
config1 = {
'user': 'USER',
'password': 'PASSWORD',
'host': 'IP',
'port': '3307',
'database': 'pdftxttest',
'raise_on_warnings': True,
}
# Direct Connection to Google Cloud SQL
config2 = {
'user': 'USER',
'password': 'PASSWORD',
'host': 'IP',
'database': 'pdftxttest',
'raise_on_warnings': True,
}
try:
cnx = mysql.connector.connect(**config1)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
print("Connection not made")
cursor = cnx.cursor()
# Test information
id = str(1)
testtitle = str("Look a fake title")
teststring = str('thislistis representingaveryshort pdfwithfuckedup spaces')
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)
try:
cursor.execute(add_pdf)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_TABLE_ERROR:
print("no pdf for you")
else:
print(err)
print("here")
cnx.commit()
cursor.close()
cnx.close()
After running this code I get
(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
File "TXT2SQL.py", line 47
try:
^
SyntaxError: invalid syntax
I have some previous experience in java but I'm still a novice programmer.
If I remove the Try...Except clause and go straight to cursor.execute() the console tells me
(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
File "TXT2SQL.py", line 46
cursor.execute(add_pdf)
^
SyntaxError: invalid syntax

You were missing a parentesis there.
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring))

In previous line
add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)
You open ( but didn't close it.

Related

Writing to MySQL using Python is not working?

I have this simple code for writing data to MySQL database.
mycursor = sql_db.cursor()
sql = "INSERT INTO users (discord_id, platform, gamertag) VALUES (%s, %s, %s)"
val = (interaction.user.id, platform.value, gamertag)
print(val)
try:
mycursor.execute(sql, val)
sql_db.commit
except mysql.connector.Error as err:
print(err)
print("Error Code:", err.errno)
print("SQLSTATE:", err.sqlstate)
print("Message:", err.msg)
mycursor.close
sql_db.close
print(mycursor.rowcount, "record inserted.")
MySQL server is hosted on VPS server
enter image description here
Console output is:
(176432554692313088, 'acti', 'jcK_#2039728')
1 record inserted.
Looks like writing was successful, but my database is still empty. Any idea what is happening or how to catch error to find out why my data are not writing to database?
I tried catch errors with this except but as you can see, it doesn't catch anything.
except mysql.connector.Error as err:
print(err)
print("Error Code:", err.errno)
print("SQLSTATE:", err.sqlstate)
print("Message:", err.msg)

Problem putting using %s in a MySQL command

I'm trying to automate (by using python scripting) the ability to create a MySQL role, but for some reason I am unable to put my string variable into mysql command. This is what I've got so far:
#!/usr/bin/python3
import mysql.connector
from mysql.connector import errorcode
# Open database connection
try:
serverHostName='localhost'
userName='root'
passwd='password'
databaseName='mysql'
roleName='reader'
cnx = mysql.connector.connect(
host=serverHostName,
database=databaseName,
user=userName,
password=passwd)
cursor=cnx.cursor(prepared=True)
dropRole="""DROP ROLE IF EXISTS %s """
print(dropRole, roleName)
#cursor.execute(dropRole, roleName)
#cnx.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
print("You have successfully disconnected from your MySQL database")
what comes out is the following:
DROP ROLE IF EXISTS %s reader
You have successfully disconnected from your MySQL database
If anyone can explain to me why %s and the reader is showing up in my print line that would be much appreciated.
You didn't call a formatting operator to subsitute roleName into the string, so it's just printing the format string. Use the % operator to perform formatting.
print(dropRole % roleName)

SQL SELECT statement is not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
def showallres():
sql = '''SELECT ResidentID,FirstName,SurName,Age,MDisability,History,Impairment,Money,Contact
FROM tblResidentM'''
results = run_sql2(sql)
print(results)
return results
for some reason it just prints 'None'? But it worked before. The table and all the fields are named correctly so I am unsure of what it is.
Here is the code for 'run_sql2'
def run_sql2(sql):
db = db_connect()
c = db.cursor()
c.execute(sql)
results=c.fetchall()
db.commit()
c.close()
db.close()
I am connecting to an online mysql database.
db_connect is as follows
def db_connect():
try:
db = mysql.connector.connect(user = 'user', password = 'pass', host = 'host', database = 'db', port = 'port')
print('connected')
return db
except mysql.connector.Error as error:
print(error)
Your function run_sql2() does not return anything,
in Python a function returns None by default, that's why results is None
def run_sql2(sql):
db = db_connect()
c = db.cursor()
c.execute(sql)
results = c.fetchall()
db.commit()
c.close()
db.close()
return results # <---- you must return the results

AttributeError: 'MySQLCursor' object has no attribute 'commit'

def fillblast(sequentie, titel_lijst, score_lijst, e_lijst, iden_lijst, pos_lijst, gaps_lijst):
conn = mysql.connector.connect(host = "ithurtswhenip.nl", user = "pg2", password = "pg2", database= "pg2", port= "3307")
cursor = conn.cursor()
Blast = 1000
for i in range(0,len(titel_lijst)):
Blast =+ 2
cursor.execute("INSERT INTO `pg2`.`Blast` (`Blast_id`, `Blast_seq`, `Blast_titel`, `Blast_score`, `Blast_E`, `Blast_gaps`, `Blast_pos`, `Blast_iden`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);", (Blast, sequentie[i] ,titel_lijst[i], score_lijst[i], e_lijst[i], iden_lijst[i], pos_lijst[i], gaps_lijst[i]))
print("1 record toegevoegd")
cursor.commit()
cursor.close()
conn.close()
I get the following error:
AttributeError: 'MySQLCursor' object has no attribute 'commit'
How does it come, and where does it go wrong?
I try to connect with MySQLWorkbench.
EDIT:
Now I get the following error:
mysql.connector.errors.DatabaseError: 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
Because you can not commit a cursor! you must commit the connection.
# cursor.commit() --> This is wrong!
conn.commit() # This is right
Check the docs...
While fixing some legacy code (that apparently hasn't been working for a couple of years, so users stopped trying to use it), we ran into the same error, using the MySQL-python package in Django. Using the suggestions on this and other answers however resulted in a different error, on account of it occurring within the Django ORM:
django.db.transaction.TransactionManagementError: This code isn't
under transaction management
So for those who run into this error after using conn.commit() instead of cursor.commit(), you may be able to use enter_transaction_management and leave_transaction_management (note that this was for Django 1.4.6 and MySQL-python 1.2.5; I may have to update this once we get the Django upgrade completed):
try:
conn.enter_transaction_management()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except DatabaseError as e:
cursor.rollback()
log.warning('log warning here')
# Handle other exceptions here.
finally:
if cursor:
cursor.close()
conn.leave_transaction_management()

how can I fix the error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm novice here and I have my code, there is running good before I create my SQL query.
I use sqlite3 as database.
that's my code :
code.py
print """<INPUT Value="Valider" Type="SUBMIT" >
<head>
<script type="text/javascript">
{
alert('thank you.');
}
</script>
</head>"""
print "</body>"
print "</html>"
conn = sqlite3.connect('database.sqlite')
conn.row_factory = sqlite3.Row
c = conn.cursor()
sql = "INSERT INTO info_calc (my_argv[2], my_argv[3], my_argv[4], sys.platform, getpass.getuser(), machine ) VALUES (%s, %s, %s, %s, %s, %s)
try:
c.execute(sql)
conn.commit()
except:
conn.rollback()
cursor.close()
when I execute my code, I have this error :
sql = "INSERT INTO info_calc (my_argv[2], my_argv[3], my_argv[4], sys.platform, getpass.getuser(), machine ) VALUES (%s, %s, %s, %s, %s, %s)
^
SyntaxError: EOL while scanning string literal
You forgot the quote at the end of the string.
Also, the INSERT statement wants a list of column names; my_argv[2] is not a column name.
Furthermore, %s is not a database parameter marker; use ? instead.
Additionally, getpass is a module; you cannot call it.
sql = "INSERT INTO info_calc (application,version,path,os,user,ip) "+
"VALUES (?,?,?,?,?,?)"
args = my_argv[2], my_argv[3], my_argv[4], sys.platform, getpass.getuser(), machine
c.execute(sql, args)
you forget to keep "
it should be like
sql = "INSERT INTO info_calc (application,version,path,os,user,ip) VALUES (%s, %s, %s, %s, %s, %s)"
one more thing,while executing the query insert you need to give values
it should be
c.execute(sql,(my_argv[2], my_argv[3], my_argv[4], sys.platform, getpass.getuser(), machine ))

Categories

Resources