For some reason, I am storing the below array completely in the SQL server using pyodbc in the form of text with single quotes.
['Sachin', 'Yuvraj']
I am inserting the above value using below code
tes_table= SQLCURSOR.execute('''INSERT INTO Test_Table(test_name) VALUES ('{}')
'''.format(arr))
I am getting the below error.
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'Sachin'. (102) (SQLExecDirectW)")
[13/Oct/2020 23:54:53] "POST /api/save HTTP/1.1" 500 77431
This is another example of why using string formatting to embed data values into SQL command text is a bad idea. In this case the rendered string literal creates a syntax error because the single quotes are not properly escaped.
>>> arr = ['Sachin', 'Yuvraj']
>>> "... VALUES ('{}')".format(arr)
"... VALUES ('['Sachin', 'Yuvraj']')"
Instead, you should be using a proper parameterized query
sql = """\
INSERT INTO Test_Table (test_name) VALUES (?)
"""
tes_table = SQLCURSOR.execute(sql, str(arr))
Related
Hello and thank you for taking the time to read this. For days I'm figuring out why I get this error when I try to load Account data towards an mssql database. The connection is fine.
But I keep on getting these errors:
(pyodbc.ProgrammingError) ('Invalid parameter type. param-index=17 param-type=collections.OrderedDict', 'HY105')
Exception: (102, b"Incorrect syntax near 'Id'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
Exception: One or more values in the dataframe have more characters than possible in the database table. The maximum number of characters in each column are:
How can I circumvent these errors and load the data without errors:
I use this for instance:
engine = sal.create_engine('mssql+pyodbc:///?odbc_connect={}'.format(params))
conn = engine.connect()
for entity in ['Account']:
df = get_salesforce_data(sf=sf, sf_object=entity, method=method)
df.to_sql(entity, con = engine, if_exists ='append', index = False, chunksize = 1000)
There 94 columns in this Account table?
Thank you for thinking with me
I'm updating the output of Google reverse geocoding (which is in JSON format),
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=mydb;UID=test;PWD=abc#123;autocommit=True')
cursor = cnxn.cursor()
wp = urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?latlng=18.5504,73.9412&sensor=false")
pw = wp.read()
#print(pw)
cursor.execute("UPDATE GEOCODE_tbl SET JSON_str = ? WHERE GEOCODE_ID = ?", pw,749904)
print('Done')
cnxn.commit()
But it gives error
('22018', '[22018] [Microsoft][ODBC SQL Server Driver][SQL Server]Operand type clash: image is incompatible with nvarchar(max) (206) (SQLExecDirectW)')
What kind of error is that?
The JSON_str column has such JSON output, so I'm executing the task for those column whose JSON_str column is NULL.
Does anyone have any idea about it?
The value pw is not of type str. Try converting your query to this:
cursor.execute("UPDATE GEOCODE_tbl SET JSON_str = ? WHERE GEOCODE_ID = ?", (str(pw), 749904))
Good luck!
I have implemented most other basic database transactions including insert,update,select with similar syntax,but on trying to delete,i get error
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
What would the correct syntax be? I must delete according to user input. Here is a shortened version of my code,minus the insert,select,update part.:
elif (choice == 4):
mail=raw_input('Enter email of user to be deleted:')
print 'Deleting..'
delete_user_details(mail)
def delete_user_details(email):
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql,email)
You need to pass query parameters to cursor.execute() as a tuple, even for a single parameter. Try this:
sql = "DELETE FROM users WHERE email = %s"
cursor.execute(sql, (email,))
I parse a database into an RDFlib graph. I now want to INSERT the triples from this graph into the GraphDB triple store. The code works fine when I execute it on an older version of GraphDB-Lite hosted on Sesame. However, I get an error while executing the same query on the now standalone GraphDB 7.0.0. The graph is partially parsed before the error is raised and the inserted triples do show up in the triple store.
This is part of the code:
graphdb_url = 'http://my.ip.address.here:7200/repositories/Test3/statements'
##Insert into Sesame
for s,p,o in graph1:
pprint.pprint ((s,p,o))
queryStringUpload = 'INSERT DATA {%s %s %s}' %(s,p,o)
# queryStringUpload = 'DELETE WHERE {?s ?p ?o .}'
# print queryStringUpload
sparql = SPARQLWrapper(graphdb_url)
sparql.method = 'POST'
sparql.setQuery(queryStringUpload)
sparql.query()
Following is the error:
ARQLWrapper.SPARQLExceptions.QueryBadFormed: QueryBadFormed: a bad request has been sent to the endpoint, probably the sparql query is bad formed.
Response:
MALFORMED QUERY: Lexical error at line 1, column 93. Encountered: "/" (47), after : "purl.org"
What is causing the error and how do I resolve it?
It was a syntax error. I had URIs starting with http:/ instead of http:// in some places.
stmt = "UPDATE requests SET (hostname,domainname,naptrsrvptrinitial,cnameptrfinal,publiclist,privatelist) = ('%s','%s','%s','%s','{%s}','{%s}') WHERE requestid = %d"%(str(myjson['hostName']),str(myjson['domainName']),str(myjson['customRecord']),str(myjson['canName']),publicArray,privateArray,int(myjson['requestID']))
curs.execute(stmt)
I have above query which is subjected to sql injection, below is query which mitigate sql injection.
curs.execute("UPDATE requests SET (hostname,domainname,naptrsrvptrinitial,cnameptrfinal,publiclist,privatelist) = (%s,%s,%s,%s,{%s},{%s}) WHERE requestid = %s",(str(myjson['hostName']),str(myjson['domainName']),str(myjson['customRecord']),str(myjson['canName']),publicArray,privateArray,int(myjson['requestID'])))
if I pass array {%s} in above query it throws an error??? How do I resolve??