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.
Related
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
Here is my code. I'm trying to insert data from a CSV into a SQL Server Table. I'm trying to follow what seems like a relatively simple example here:
https://datatofish.com/import-csv-sql-server-python/
import pandas as pd
import pyodbc
data = pd.read_csv(r'C:\Users\Steve\Documents\Datasets\covidgeography.csv')
df = pd.DataFrame(data, columns=['MMSA', 'total_percent_at_risk', 'high_risk_per_ICU_bed', 'high_risk_per_hospital',
'icu_beds', 'hospitals', 'total_at_risk'])
print(df)
conn = pyodbc.connect('Driver={SQL Server};'
'Server=STEVELAPTOP;'
'Database=AdventureWorks2017;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
#cursor.execute('CREATE TABLE dbo.covidgeo(MMSA nvarchar(250),total_percent_at_risk nvarchar(250),'
# 'high_risk_per_ICU_bed nvarchar(250), '
# 'high_risk_per_hospital nvarchar(250),icu_beds nvarchar(250),hospitals nvarchar(250),total_at_risk '
# 'nvarchar(250))')
for row in df.itertuples():
cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
high_risk_per_hospital,icu_beds,hospitals,total_at_risk) VALUES (???????)
''',
row.MMSA,
row.total_percent_at_risk,
row.high_risk_per_ICU_bed,
row.high_risk_per_hospital,
row.icu_beds,
row.hospitals,
row.total_at_risk)
conn.commit()
After I run this I get this error:
Traceback (most recent call last):
File "C:\Users\Steve\PycharmProjects\DataLearning\DataImport.py", line 20, in <module>
cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "#P1#P2#P3#P4#P5#P6#P7". (137) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)')
Do I have a syntax error in how I'm writing the insert statement?
It was a syntax error. I had to change:
VALUES (???????)
to
VALUES (?,?,?,?,?,?,?)
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)")
I'm having trouble connecting to a MS SQL Server database via Python using pyODBC:
import pyodbc
conn = pyodbc.connect(('DRIVER={SQL Server};'
'SERVER=tmw-prod-lo\\SQL65;'
'DATABASE=TMWSuite;'
'UID=VENTURE\\acoop;'
'PWD=RaNdoM!'))
This results in:
InterfaceError: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'VENTURE\\acoop'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'VENTURE\\acoop'. (18456)")
I'm pretty confident I've got all the parameters right and that I need to escape the backslashes in the server and username as above, correct? So it just looks like a permissions issue but I wanted to rule out any other issues first.
I'm trying to use pyodbc within Python to import a few values into my SQL server DB.
for data_form in data['matches']:
connprod = pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};Server=tcp:*****.database.windows.net,1433;Database=League_Stats;Uid=******;Pwd=******;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;')
cursorprod = connprod.cursor()
lane= str(data_form['lane'])
gameId= str(data_form['gameId'])
champion= int(data_form['champion'])
platformId= str(data_form['platformId'])
timestamp= str(data_form['timestamp'])
queue= str(data_form['queue'])
role= str(data_form['role'])
season= str(data_form['season'])
UPDATE_SQL = """\
INSERT INTO MATCH_HISTORY_LIST
(lane, gameId, champion, platformId, timestamp, queue, role, season)
VALUES
(?,?,?,?,?,?,?,?,)
"""
print '--------------'
print "INSERT INTO Match_History_List(lane, gameId, champion, platformId, timestamp, queue, role, season) VALUES(?,?,?,?,?,?,?,?,)", lane,gameId,champion,platformId,timestamp,queue,role,season
cursorprod.execute(UPDATE_SQL, (lane,gameId,champion,platformId,timestamp,queue,role,season))
cnxn.commit()
This is the error I'm getting:
Traceback (most recent call last):
File "C:\Users\rybau\Desktop\Parse Json.py", line 60, in <module>
cursorprod.execute(UPDATE_SQL, (lane,gameId,champion,platformId,timestamp,queue,role,season))
ProgrammingError: ('42000', u"[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)")
I have no idea where the ) is coming from. I've tried just printing the statement and manually running it against the DB and it works successfully.