在MySQL查询中使用Python变量 [英] Using a Python variable in MySQL query

查看:362
本文介绍了在MySQL查询中使用Python变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数采用下面编写的函数placeholder()中编写的变量,然后在 MySQL 查询中使用该变量.我在下面写了一个例子:

I am trying to write a function that takes the variable written in the function placeholder() written below and then uses that in MySQL queries. I have written up an example below:

import MySQLdb
connection = MySQLdb.connect(host = "localhost", user = "root", 
                   passwd = "", db = "cars")
cursor = connection.cursor()

def placeholder(placeholder_variable):
    sql = "TRUNCATE TABLE %s"
    cursor.execute(sql, placeholder_variable)

placeholder('car_brands')

当我尝试运行该程序时,出现以下错误:

When I try to run this program I get the following error:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''car_brands'' at line 1")

这是用于大学作业,必须使用placeholder('variable')格式来接收变量.我花了数小时在互联网上搜索,试图找到解决方案,请帮助:/

This is for a university assignment and MUST use the placeholder('variable') format to receive the variable. I have spent literally hours searching the internet trying to find a solution to this please help :/

推荐答案

sql = "TRUNCATE TABLE " + placeholder_variable + ";"
cursor.execute(sql)

这篇关于在MySQL查询中使用Python变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆