Home > Database > Mysql Tutorial > body text

How Do I Correctly Execute a MySQL Update Statement with Variables in Python?

DDD
Release: 2024-11-08 19:46:02
Original
439 people have browsed it

How Do I Correctly Execute a MySQL Update Statement with Variables in Python?

Pitfalls to Avoid: Correcting Python MySQL Update Statement with Variables

When attempting to execute MySQL update statements in Python, it's essential to ensure proper syntax and data handling. This question highlights specific errors made in an incorrect statement.

The Incorrect Statement:

The initial code provided suffers from several issues:

cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)
Copy after login

Errors and Modifications:

  1. Lack of Quotation Marks: The entire statement should be enclosed in triple or double quotation marks to indicate a multi-line string.
  2. Incorrect Comma Syntax: When using multiple assignments, commas should separate variables and not string values.
  3. Missing Arguments: The "Minute" value is missing its variable name after the comma.

The Corrected Statement:

The correct syntax for the update statement is:

cursor.execute ("""
   UPDATE tblTableName
   SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
   WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
Copy after login

Another option involves basic string manipulation:

cursor.execute ("UPDATE tblTableName SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s WHERE Server='%s' " % (Year, Month, Day, Hour, Minute, ServerID))
Copy after login

Cautionary Note:

While the latter method works, it's advisable to avoid this practice due to potential SQL injection vulnerabilities. The recommended approach is to use parameter substitution as demonstrated in the first example.

The above is the detailed content of How Do I Correctly Execute a MySQL Update Statement with Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template