Python 插入 %s MySQL

标签 python mysql

我正在尝试使用变量 test 作为表名将一些数据插入数据库。但不幸的是我似乎无法实现这一点。谁能帮我吗?

从我的加薪中我得到:

TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'

我的代码:

   test = "hello"
   # Open database connection
    db = MySQLdb.connect("127.0.0.1","admin","password","table" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # Prepare SQL query to INSERT a record into the database.
    sql = ("""INSERT INTO %s (name,
            age, gender)
            VALUES (%s, %s, %s)""",(test))
    try:
        # Execute the SQL command
        cursor.execute(sql, (name, age, gender))
        db.commit()
    except:
        raise
        db.rollback()


    # disconnect from server
        db.close()

最佳答案

我认为 MySQLdb 不允许您使用表名称参数 - 通常这用于实际参数(有时来自用户输入并且需要清理的参数 - 名称/年龄/性别部分正确)。您可以使用 Python 的字符串格式来实现此目的:

sql = ("""INSERT INTO {table} (name, age, gender)
          VALUES (%s, %s, %s)""".format(table=table), (test))

关于Python 插入 %s MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706251/

相关文章:

python - 在没有开始标签的情况下如何从汤中提取数据?

python - Selenium webdriver(python) 中隐藏的 HTML 元素

php - 显示mysql中的特定行

php - 照片上传到服务器和数据库的问题

sql - 带复杂连接子句的左连接

python - 如何让 np.where 接受更多参数,以便它过滤 >、< 和 =;不仅仅是 > 和 <?

python - 按索引列表进行字符串切片

php - 左连接mysql与三个表

MySQL - 大表的基本问题

python - Django:过滤自引用外键属性