0

I have this query:

query_del = '''DELETE * FROM Students WHERE Students.[last_name] = "Q";'''

And I'm doing this for execute:

conn= pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\XXX\Database.accdb;')

curs = conn.cursor()
curs.execute(query_del)
curs.commit()

But I'm getting this error:

ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1

The database is current like:

ID last_name first_name E-mail Address

3 Buuuu B C
4 Cuuuu C D
70 W W
72 W W
74 W W
76 W W
78 W W
80 W W
82 W W
84 W W
86 W W
87 Q Q
88 W W
89 Q Q
90 W W

EDIT 1: The query this way works:

query_del = '''DELETE * FROM Students WHERE Students.[last_name] = 'Q';'''

But I really need to have double quotes in the variables because I have some last names like x'xxx'x so I don't know how to DELETE them. The query with simple a double quotes works well in Access:

DELETE FROM Students WHERE Students.[last_name] = "W"; #Works in Access
DELETE FROM Students WHERE Students.[last_name] = 'W'; #Also Works in Access

How can I translate this to python and to pyodbc?

Anabel
  • 33
  • 8
  • Regarding the issue with text values which include an apostrophe, switch to a [parameter query](https://stackoverflow.com/a/64209618/77335) – HansUp Aug 20 '21 at 15:06

1 Answers1

1

Consider:
query_del = "DELETE FROM Students WHERE [last_name] = 'Q'"

Notice the swap of quote and apostrophe delimiters. The * wildcard for fields is not necessary although shouldn't hurt.

If hard coding a value with apostrophe then double the aprostrophe so it is escaped and forced to be seen as literal text: ='x''x'. If coding a dynamic input by referencing a control on form, must concatenate and use Replace to handle possibility of apostrophe in data:

query_del = "DELETE FROM Students WHERE [last_name] = '" & Replace(Me.tbxName, "'", "''") & "'"

Or use parameters - review How do I use SQL parameters with python?

The variable set is query_del but execute references query so try:
curs.execute(query_del)

June7
  • 19,874
  • 8
  • 24
  • 34
  • The reason this works, of course, is that the ODBC driver has ANSI quotes on by default, so is interpreting `"Q"` as a field name, not as a literal string – Erik A Aug 19 '21 at 09:22
  • So what if I want to delete a last name that is: x'xxx? I can't do it with 'x'xxx', I need to do it like "x'xxx" – Anabel Aug 20 '21 at 06:15