擅长:python、mysql、java
<p>我想这就是你要找的。</p>
<pre><code>def connect_and_get_data(query, data):
...
cursor.execute(query, data)
...
def get_data_about_first_amazing_topic(useful_string):
query = "SELECT ... FROM ... WHERE ... AND some_field=%s"
connect_and_get_data(query, ("one","two","three"))
...
</code></pre>
<p>但是,如果您要快速进行几个查询,最好重用您的连接,因为建立太多连接可能会浪费时间。</p>
<pre><code>...
CONNECTION = MySQLdb.connect(host=..., port=...,
user=..., passwd=..., db=...,
cursorclass=MySQLdb.cursors.DictCursor,
charset = "utf8")
cursor = CONNECTION.cursor()
cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", ("first", "amazing", "topic"))
first_result = cursor.fetchall()
cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", (("first", "amazing", "topic")))
second_result = cursor.fetchall()
cursor.close()
...
</code></pre>
<p>这将使您的代码执行得更好。</p>