I am trying to insert/append into access a dataframe using pyodbc. However; when I run the code, I get an error: ProgrammingError: ('The SQL contains 21 parameter markers, but 1 parameter were supplied', 'HY000')
my sample code is: for row in tDjango: cursor.execute( 'INSERT INTO TDjango (Eid, Eventtype, Location, Lat, Lon, Created, TMCClosed,FirstArrival(min), PatrolArrival(min), TowArrival(min), LanesCleared(min), RoadwayCleared(min),Camera, DayofWeekOpened, DayofWeekClosed, sameDay, confirmClosed, confirmFirstAr, confirmPtrl, confirmTow, confirmLnClear) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',tDjango) conn.commit()
I’m not entirely sure what I am missing in the SQL statement to make the error go away.
Instead of using cursor.execute(), I used cursor.executemany().
Related
I am new in using python API to send a query to mysql.
My issue is very easy to reproduce. I have a table named "ingredient" and I would like to select the rows from python using parameters
If I do cursor.execute("select * from ?",('ingredient',)) I get the error message : Error while connecting to MySQL Not all parameters were used in the SQL statement MySQL connection is closed
I I do cursor.execute("select * from ?",'ingredient') I get the error message : Error while connecting to MySQL 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 '?' at line 1
Same issues using %s instead of ?. Using the other type of single quote on 'ingredient' instead of 'ingredient' does not give results either.
How is this supposed to work here ?
You just can't pass a table name as parameter to a query. The parameterization mechanism is there to pass literal values, not object names. Keep in mind that the database must be able to prepare the query plan from just the parameterized string (without the actual parameter value), which disqualifies using metadata as parameter.
You need string concatenation instead:
cursor.execute("select * from " + yourvar);
Note that, if the variable comes from outside your program, using such contruct exposes your code to SQL injection. You need to manually validate the value of the parameter before execting the query (for example by checking it against a fixed list of allowed values, or by querying the information schema of the database to ensure that the table does exist).
Does your query work if you just write:
cursor.execute("SELECT * FROM ingredient")
?
I am trying to insert values into a row of mysql database in a way that not be vulnerable to injection, but gives my syntax error. This is a piece of my code which causes the error:
cursor.execute("INSERT INTO api.mytable(id) VALUES (:id);", {"id": 1})
and error:
ERROR in connection: (1064, "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 ':id)' at line 1")
code you please tell me what's the wrong with my code?
I am assuming id is given as some kind if input! Hence you can always check for the required format and allow only required ones! This is to avoid SQL injection!. Hence the natural formatting as shown below should do the job! And this is very basic level checking!
id_in = input("Here is the id taken " ) ## can be through any source . It is just an example
if isinstance(id_in,int): ##Please mention the required format here I am assuming it as integer
cursor.execute("INSERT INTO api.mytable(id) VALUES (%s);", (id_in))
else:
##do some stuff here
i am a novice at python and sql so i have encounterd some issue while trying to create a stored procedure and passing values to it.
i have looked through few questions here.Of what i could understand i used the ODBC format and it works for procedures not requiring anything to be passed. The query is simple. it takes in 2 parameters route_no and month. the query then count the number of trios taken by a bus per date for that month on that route.
if __name__ == "__main__":
conn=pyodbc.connect('''Driver={SQL Server};'''
'''Server=ABY;'''
'''Database=testing;'''
'''Trusted_Connection=yes;''')
cursor=conn.cursor()
proc3="""CREATE PROCEDURE TRIPS_PER_DAY #ROUTENO NVARCHAR(30),#MONTH NVARCHAR(30)
AS
BEGIN
SELECT [ON DATE],SUM(DISTINCT([TRIP NO])) AS SUM_TRIPS
FROM testing.dbo.sheet1$
WHERE [ROUTE NO#]=#ROUTENO AND MONTH([ON DATE])=#MONTH
GROUP BY [ON DATE]
END"""
drop_proc3="""IF EXIST(SELECT * FROM SYS.OBJECTS WHERE TYPE='P' AND NAME='TRIPS_PER_DAY') DROP PROCEDURE TRIPS_PER_DAY"""
call_proc3="""{CALL testing.dbo.TRIPS_PER_DAY(?)(?)}"""
cursor.execute(drop_proc3)
cursor.execute(proc3)
values=('16','11-11-2017')
dff=pd.read_sql(call_proc3,conn,params=(values,))
print(dff)
this is the error i am getting:
DatabaseError: Execution failed on sql '{CALL testing.dbo.PASS_PER_STOP(?)(?)}': ('42000', '[42000] [Microsoft][ODBC SQL Server Driver]Syntax error or access violation (0) (SQLPrepare)')
i am not sure if the method i am using is right or if there is a syntax error.
I am also not sure how to pass values and return results from the procedure using python. Any help?. Thanks in advance!!!
I have data that I need to insert into SQL Server in a list
values = [('Hello', 'McDonald'), ('Hi', 'Jennifer'), ('Ola', 'Janice'),('Hey', 'Bob')]
And I' trying to insert this using the following command:
columns_list_template = ','.join('[%s]'*len(noofcolumns)) # In this case 'noofcolumns' = 2
sql = 'INSERT INTO test VALUES ({0})'.format(columns_list_template)
cursor.execute(sql,values)
And I get the following error when I execute the code:
pypyodbc.ProgrammingError: ('HY000', 'The SQL contains 0 parameter markers, but 10 parameters were supplied')
I'm really stuck and don't know where there is an error.
PS. The list can contain more than 100000 records also. It's very dynamic
EDIT:Thank you everyone for trying to help me out. I had different datatypes defined in source and destinations and hence the problem. Couldn't have found it out myself. Thanks for always helping me out
I have a python script that makes a call to an API, submits a request, and then is supposed to insert the result into a Sql Server 2012 table. When it goes to execute the insert into SQL, it breaks. I am currently importing json, requests, and pyodbc into the file. Here is the location where it is breaking:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER={localServer};DATABASE={localDB}')
cursor = conn.cursor()
for record in response:
print(json.dumps(record))
cursor.execute("Insert Into Ticket_Info values ?", json.dumps(record))
cursor.commit()
cursor.close()
conn.close()
It is at the cursor.execute() line where the breakage occurs. This is the error I got when I attempted to run this.
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)"
Any help I could get I would appreciate. I have searched and tried several different methods at this point, the only thing that changes is the error.
The second argument to cursor.execute() must be a sequence of values to interpolate, one for each SQL parameter in your statement.
You gave ODBC a string instead, which is also a sequence, but one that contains (many) more elements (characters) than your query requires.
Use a single-element tuple here:
cursor.execute("Insert Into Ticket_Info values (?)", (json.dumps(record),))
I also put parenthesis around the values section, as per the SQL Server INSERT syntax:
VALUES
Introduces the list or lists of data values to be inserted. There must be one data value for each column in column_list, if specified, or in the table. The value list must be enclosed in parentheses.
Unless Ticket_Info has only one column per row (unlikely, you'd have a primary key column at least), you probably need to specify what column you are inserting your value into:
cursor.execute("Insert Into Ticket_Info (<columnname>) values (?)", (json.dumps(record),))
where you need to replace <columnname> with the actual column name in your table.