Getting incorrect syntax for SQL statement in python - python

When I run below code which incorporates TOP ? in a select statement and I am unable to resolve.
Code:
cnt = self.getCount()
#cnt = 2
query = "select distinct top ? id, indicator from [TABLE] ORDER BY id ASC"
connsql = self.sql_connection()
resultset = connsql.cursor().execute(query, cnt).fetchall()
connsql.cursor().commit()
connsql.close()
I get this syntax error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '#P1'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")

Related

The SQL contains 0 parameter markers, but 1 parameters were supplied | pyodbc

I am trying to send a data from my code to SQL Server, but i got this error:
ProgrammingError:
('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'emotion'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
My Code:
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-T7OFQV6\SQLEXPRESS1;'
'Database=VidgaEmotionRecognition;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('''INSERT INTO FaceEmotion emotion ?''', index_pred_as_int)
index_pred is a value from previous code snippet.
Structure of FaceEmotion table is like this:
Column: emotion - nvarchar(50) - allows nulls
Column: _id - int - key identity

SQLAlchemy Core - Subquery missing an alias

I was working on a straightforward SQLAlchemy Core (Python 3.x) count unique query using the following code:
table_object = sqlalchemy.Table(table_name, metadata, autoload=True, autoload_with=engine, schema=schema)
agg_fields = [get_column_correct_case(table_object, col) for col in agg_fields]
agg_col_obj = [table_object.c[col] for col in agg_fields]
agg_query = sqlalchemy.select(agg_col_obj).select_from(table_object)\
.group_by(*agg_fields).count()
engine.scalar(agg_query)
While I believe this should be valid SQLAlchemy Core code, its execution returned a PYODBC error:
(pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]
Incorrect syntax near ')'. (102) (SQLExecDirectW);
[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)")
The SQL query generated by this code which failed to execute properly was:
[SQL: SELECT count([ACCOUNT]) AS tbl_row_count
FROM (SELECT dbo.history.[ACCOUNT] AS [ACCOUNT], dbo.history.[RTXNNBR] AS [RTXNNBR]
FROM dbo.history
GROUP BY dbo.history.[ACCOUNT], dbo.history.[RTXNNBR])]
Running the query directly in SQL Server, it appears to be failing because the nested select is missing an alias. Is this a bug? If not, how do I fix this code?
I figured out the answer. I was surprised it was necessary, but this can be resolved by giving the query to be counted an alias.
So
agg_query = sqlalchemy.select(agg_col_obj).select_from(table_object)\
.group_by(*agg_fields).count()
becomes:
agg_query = sqlalchemy.select(agg_col_obj).select_from(table_object)\
.group_by(*agg_fields).alias('a').count()
which now works.

[SQL Server]Statement(s) could not be prepared

here's my code
import pyodbc
username = 'abcdefg'
newPassword = 'xyz1234!'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=abc.database.windows.net;DATABASE=master;UID=yyzzyy;PWD=abcd1234!')
cursor = cnxn.cursor()
cursor.execute("ALTER LOGIN ? WITH PASSWORD = ?", username, newPassword)
I am getting the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
Server Driver][SQL Server]Incorrect syntax near '#P1'. (102)
(SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL
Server]Statement(s) could not be prepared. (8180)")
I cannot use %s or fstring as it risks SQL Injection. have to make do with markers(?). Please help me fix this.
LOGIN cannot be parametrised; you'll need to use dynamic SQL for this. I would guess this would work for you, it will from a SQL point of view (I don't know enough about python to suggest if the problem is in that code).
DECLARE #SQL nvarchar(MAX) = N'ALTER LOGIN ' + QUOTENAME(?) + N' WITH PASSWORD = N' + REPLACE(?,'''','''''') + N';';
EXEC sp_executesql #SQL;

Creating stored procedure in MS SQL through pyodbc

I am trying to create a store procedure in master in mssql through python code. The following is my code:
import pyodbc
conn = pyodbc.connect("driver={SQL Server};server=localhost; database=master; trusted_connection=true",
autocommit=True)
cursor = conn.cursor()
sqlcommand = """
USE master
GO
CREATE PROCEDURE sp_myCustomSystemProc
AS
BEGIN
PRINT 'myCustomCode'
END
GO
EXEC sp_ms_marksystemobject 'sp_myCustomSystemProc'
"""
cursor.execute(sqlcommand)
cursor.commit()
conn.commit()
After running this python code, I am getting this error:
Traceback (most recent call last):
File "auto_complete.py", line 27, in <module>
cursor.execute(sqlcommand)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]
Incorrect syntax near 'GO'. (102) (SQLExecDirectW);
[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch. (111);
[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]
Incorrect syntax near 'GO'. (102);
[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]
Incorrect syntax near 'sp_myCustomSystemProc'. (102)")
Can anyone please help me to resolve this?
Since your connection string already specifies the master database (i.e. database=master;), simply remove
USE master
GO
from your query.

Incorrect syntax near 's' in pyodbc

Sometimes I get this error randomly when I try to insert data in to the database. I fetch the data with using request.get and parsing the JSON data.
This is the error that I get:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17
for SQL Server][SQL Server]Incorrect syntax near 's'. (102)
(SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL
Server][SQL Server]Unclosed quotation mark after the character string
')'. (105)")
This is my code:
for product in parsed['products']:
cursor.execute("INSERT INTO dbo.producten (productid, datum_toegevoegd, naam, prijs_excl, prijs_incl, gewicht) VALUES ('%s','%s','%s','%s','%s','%s')" %(product['id'],product['created_at'], product['nl']['title'],product['price_excl'],product['price_incl'],product['weight']))
You must not use string interpolation for SQL queries. The db-api will do correct parameter substitution for you - replace that % with a comma.
cursor.execute('SELECT.... ', (product['id'],product['created_at'...))
# ^
cursor.execute('SELECT.... product = ?', (value_for_product))
works for python 3.^

Categories

Resources