cursor.execute("DROP DATABASE ?", (databasename,))
I am using python3 with pyodbc driver. Only facing issue while create and delete database. other operations like select are working fine.
Getting below error:
pyodbc.ProgrammingError: ('42000', u"[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '#P1'. (102) (SQLExecDirectW)")
In order to sanitize your data you can use SQL Server QUOTENAME to returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.
You also need to set autocommit=True in your pyodbc connection to allow dropping of databases.
conn = pyodbc.connect("DRIVER={SQL Server};"
"SERVER="+server+";"
"UID="+username+";"
"PWD="+password,
autocommit=True)
cursor = conn.cursor()
your_database_name = "YOUR_DB_NAME"
sql_drop = (
"DECLARE #sql AS NVARCHAR(MAX);"
"SET #sql = 'DROP DATABASE ' + QUOTENAME(?);"
"EXEC sp_executesql #sql"
)
cursor.execute(sql_drop, your_database_name)
Related
I am trying to execute below SQL query by introducing 2 variables in Python but getting error,
Original Query:
ALTER DATABASE db1 MODIFY (SERVICE_OBJECTIVE = 'DW300');
I want to use variables for db1 and 'DW300'. I have tried below statement in Python and got error.
dwu = 'DW100'
sqlpool = 'db1'
cursor.execute("""ALTER DATABASE ? MODIFY (SERVICE_OBJECTIVE = ?) """, (sqlpool, dwu))
Error: pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '#P1'. (102) (SQLExecDirectW)")
I use sqlite and it accepts this answe.
try the use of fstrings
f"""Alter Database {sqlpool} modify (service objective = {dwu}) """
I am looking to connect python to an Access database with the following code:
connStr = (
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=O:\Architecture\DAART\Data Analytics Team\DAART.accdb;"
)
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()
df = pd.read_sql("select * from APMS SV-8 Report", cnxn)
For the last line of code, I am receiving the following error message:
DatabaseError: Execution failed on sql 'select * from APMS SV-8 Report': ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in FROM clause. (-3506) (SQLExecDirectW)')
Access SQL requires you bracket table names if they contain spaces, keywords or special characters:
select * from [APMS SV-8 Report]
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;
I am using pyodbc in python 2.7 with MS SQL Server 2008R.
Here is my code for creating a database (the SQL code which works fine in SQL alone, but crash when executed in python)
SQL_command = """
IF EXISTS(SELECT * FROM sys.databases WHERE [name] = 'NewDatabase')
DROP DATABASE NewDatabase
"""
conn.cursor.execute(SQL_command)
SQL_command = """
CREATE DATABASE NewDatabase
ON
(
NAME = 'NewDatabase_data'
, FILENAME='D:\MSSQL\DATA\NewDatabase_data.mdf'
, SIZE = 4096KB
, FILEGROWTH = 4096KB
)
LOG ON
(
NAME = 'NewDatabase_log'
, FILENAME='D:\MSSQL\LOG\NewDatabase_log.ldf'
, SIZE = 4096KB
, FILEGROWTH = 10%
)
COLLATE SQL_Latin1_General_CP1_CI_AS
"""
conn.cursor.execute(SQL_command)
SQL_command = """
ALTER DATABASE
NewDatabase
SET RECOVERY SIMPLE
"""
conn.cursor.execute(SQL_command)
However, I've got following error message:
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL
Server Driver][SQL Server]CREATE DATABASE statement not allowed within
multi-statement transaction. (226) (SQLExecDirectW)')
May I know what is wrong with my code?
Many thanks.
====================================================================================
So, after taking the advice from #Matthias, I've executed commit after the drop database, then the error message became:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL
Server Driver][SQL Server]CREATE FILE encountered operating system
error 123(failed to retrieve text for this error. Reason: 15105) while
attempting to open or create the physical file
'D:\MSSQL\DATA\NewDatabase_data.mdf'. (5123)
(SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL
Server]CREATE DATABASE failed. Some file names listed could not be
created. Check related errors. (1802)")
I try to do an update query using a left join on another mdb.
Into a cursor for the first MDB, I execute this query:
update table as ori
left join (select *
from param in "E:/Jeter/param_141114.mdb"
where zone = '1H005') param
on ori.dep_sur = param.dsu_co
set ori.texture = param.textu where mid(ori.type,4,1) in ('0','7','8')
When I launch this query from Microsoft Access, no problem, the query is applied.
When I launch this query from python 2.7 with pyodbc, here my result translated from french:
ProgrammingError ('42000', "[42000] [Microsoft] [ODBC Microsoft Access
Driver] The database engine can not find [E: /Jeter/param_141114.mdb]
'Make sure the name. parameter or alias is valid, he does not
understand character or incorrect punctuation and that it is not too
long. (-1002) (SQLExecDirectW) ")
Some ideas?
Apparently the SELECT ... FROM TableName IN "FileName" ... syntax is not available to ODBC queries from external applications. However, I just tried the following variation and it worked for me (Python 2.7 and pyodbc):
sql = """
update tableau as ori
left join (select *
from [C:/__tmp/test.mdb].param
where zone = '1H005') param
on ori.dep_sur = param.dsu_co
set ori.texture = param.textu
"""
crsr = db.execute(sql)
crsr.commit()