0

im trying to insert values into a column that a user has asked to be changed which is called surnamereq and the user change which is called name1. money_spent is the name of the table and first_name is the column that the user is changing the value of.

This is how it should be written in SQL(i think):

INSERT INTO money_spent(first_name) WHERE last_name = surnamereq VALUES(name1)

This is what ive got in python:

cursor.execute("INSERT INTO money_spent(first_name) WHERE last_name = ?, surnamereq VALUES(name1)")

Thanks

5
  • If you are updating an existing row in the table then you need to use an UPDATE statement, not an INSERT statement. (INSERT is for adding a new row.) Commented Dec 14, 2018 at 21:26
  • I have this now: Commented Dec 15, 2018 at 10:19
  • cursor.execute(""" UPDATE money_spent SET first_name = ?, fname WHERE last_name = ?, surnamereq""") Commented Dec 15, 2018 at 10:19
  • And that gives me a pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect (17) (SQLExecDirectW)') Commented Dec 15, 2018 at 10:20
  • It might be a problem because im using python variables in the cursor.execute command, if so how should i have an input for the user to assign a variable to? Commented Dec 15, 2018 at 10:24

1 Answer 1

1

The documentation for the .execute method shows that the form of the method call is

execute(sql, *parameters)

and states that

The optional parameters may be passed as a sequence, as specified by the DB API, or as individual values.

So, you could either do

surnamereq = 'Thompson'
fname = 'Gord'
#
sql = "UPDATE money_spent SET first_name = ? WHERE last_name = ?"
params = (fname, surnamereq)
cursor.execute(sql, params)

or

surnamereq = 'Thompson'
fname = 'Gord'
#
sql = "UPDATE money_spent SET first_name = ? WHERE last_name = ?"
cursor.execute(sql, fname, surnamereq)

Note that the second approach is a pyodbc-specific extension to the DB API.

Sign up to request clarification or add additional context in comments.

2 Comments

What should i do if i get a Previous SQL was not a query. Error?
It does it when i use the for row in cursor.fetchall(): print (row) command at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.