有人知道我在哪里错吗?数据库更新的语法在我看来是正确的。我也想知道是否需要关闭连接,例如在每个函数中打开和关闭连接。例如,让我们说一个函数执行不同类型的DB命令,一个函数用于插入,一个函数用于更新,一个函数用于删除,就像一个通用示例一样。
输出:
query
我的代码:
[root@localhost student_program]# python modify_student.py
Connection successful!!
Enter the id of the student record you wish to modify: 21
Is this student personal information you want to modify - y or n: y
Enter the first name: Jake
Enter the last name: Mc Intyre
Enter the email address: jake@noemail.com
Enter the address: 300 Main Street, New York
Enter the DOB in YYYY-MM-DD: 1960-01-01
Traceback (most recent call last):
File "modify_student.py", line 38, in <module>
modify_student()
File "modify_student.py", line 29, in modify_student
cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])
File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 893, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1103, in _read_query_result
result.read()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1396, in read
first_packet = self.connection._read_packet()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1059, in _read_packet
packet.check_error()
File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(firstname, lastname, email, address, DOB)VALUES ('Jake','Mc Intyre','jake@noema' at line 1")
答案 0 :(得分:2)
更新的语法是:
UPDATE tablename SET name='%s', email='%s' WHERE id='%s'
您正在尝试像INSERT一样进行更新。但是UPDATE仅支持单独设置每个列名,而不支持设置列列表。
尝试:
sql = "UPDATE students_info SET firstname='%s', lastname='%s', email='%s', address='%s', DOB='%s' WHERE ID='%s'"
cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])
答案 1 :(得分:0)
查询语句也不正确。试试这个
sql = 'UPDATE students_info SET firstname="'+firstname+'", lastname=="'+lastname+'", email="'+email+'", address="'+address+'", DOB="'+address+'") Where id="'+student_id+'"'
希望这会有所帮助。