将mysql\u查询从PHP转换为Python?

2024-04-20 15:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

无论如何,有没有把这一行从PHP转换成python,如果有,请解释每一件事的含义和它是如何工作的。你知道吗

mysql_query( "INSERT INTO chatitems VALUES ( null, null, '".
    mysql_real_escape_string( $_REQUEST['user'] ).
    "', '".
    mysql_real_escape_string( $_REQUEST['message'] ).
    "')" );

我遇到了很多麻烦,试着去做

import MySQLdb

conn = MySQLdb.connect(host='24.44.205.122', user='root', password='1234',
                          database='chat')
x = conn.cursor()

try:
    x.execute("INSERT INTO chatitems VALUES (%s, %s)""", (null, null), conn.escape_string(self.request.get("user")). "', '". conn.escape_string(self.request.get("message")). "')" );
except:
    conn.rollback()

conn.close()

如果有人能解释怎么做,那将是一个很大的帮助


Tags: selfmessagestringrequestmysqlconnrealnull
1条回答
网友
1楼 · 发布于 2024-04-20 15:24:04

如果使用parameter passing style,dbapi将负责escape。您不需要逃避自己,构建sql:

x.execute("INSERT INTO chatitems VALUES (null, null,  %s, %s)", [
    self.request.get("user"),
    self.request.get("message")
])

The term bound refers to the process of binding an input value to a database execution buffer. In practical terms, this means that the input value is directly used as a value in the operation. The clientshould not be required to "escape" the value so that it can be used — the value should be equal to the actual database value.

相关问题 更多 >