Python与MYSQL

2024-04-26 21:25:55 发布

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

我正在尝试编写一个函数,在这个函数中我可以传入一个变量(当函数被调用时),并且这个变量可以以某种方式传递到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) 

Tags: 函数nameselfdbsqldatedefcreate
2条回答

很简单:)

您有两个选择,但是我建议您使用字符串格式函数。你知道吗

def create_table(self, name): 
     # you can use multiline string """ which makes it easier to read.
     # notice {0}. That is a place you want to insert first value passed to 'format' function.
    sql = (
        """
        CREATE TABLE IF NOT EXISTS ({0})
        (id int auto_increment primary key, date date,
         open float, high float, low float, close float,
         volume float)"
        """.format(name)
       )
    self.mycursor.execute(sql)
    self.connection.commit()

在这里寻找更多的创意。% vs format

首先,在create_table中根本没有使用name。其次,不能像这样参数化表名。您需要使用format之类的内容来插入表名,例如"CREATE TABLE IF NOT EXISTS {}".format(name)等等。并且,根据输入的来源,您需要对输入进行清理。你知道吗

相关问题 更多 >