我正在尝试编写一个函数,在这个函数中我可以传入一个变量(当函数被调用时),并且这个变量可以以某种方式传递到MYSQL语句中。你知道吗
当我需要向表中添加值时,我可以这样做,但是当使用变量命名表时,它不起作用。你知道吗
请检查下面的代码:
非常感谢 K公司
def __init__(self):
self.connection = pymysql.connect(host='localhost',
user='root',
password='Mandy123',
db='connectiontest',
cursorclass=pymysql.cursors.DictCursor)
self.mycursor = self.connection.cursor()
def create_table(self, name):
sql = (
"CREATE TABLE IF NOT EXISTS (%S) "
"(id int auto_increment primary key, date date, "
" open float, high float, low float, close float, "
" volume float)"
)
self.mycursor.execute(sql)
self.connection.commit()
name= input('what is the sql table name ? ')
db= sql_manager()
db.create_table(name)
很简单:)
您有两个选择,但是我建议您使用字符串格式函数。你知道吗
在这里寻找更多的创意。% vs format
首先,在
create_table
中根本没有使用name
。其次,不能像这样参数化表名。您需要使用format
之类的内容来插入表名,例如"CREATE TABLE IF NOT EXISTS {}".format(name)
等等。并且,根据输入的来源,您需要对输入进行清理。你知道吗相关问题 更多 >
编程相关推荐