无法使用mysql.connector将值插入mysql服务器

时间:2018-02-23 05:58:36

标签: python sql mysql-python

我在类实现中使用以下函数来插入值为username_sipadress_s等的MYSQL数据库,其中包含列usernameipadress等等但是我不断收到以下错误

  

mysql.connector.errors.ProgrammingError:1054(42S22):未知列   ' username_s'在'字段列表'

混淆是列名与列值的交换

def insert_server(self , username_s , ipadress_s , BLACKLISTED_s , clientid_s):
    self.connect.database = self.m_database

    self.cursor.execute(
        "INSERT INTO server"
        " ( username , ipadress , blacklisted , clientid )"
        "VALUES ( username_s , ip_adress_s , BLACKLISTED_s , clientid_s)")

1 个答案:

答案 0 :(得分:0)

MySQL会解释' username_s' VALUES中的其他名称作为文字列名,因为没有格式代码表明这些实际上是变量。您可以查看MySQL文档Inserting data using Connector/Python中的示例。需要澄清的是,这是一个简短的MWE:

import sqlalchemy

# insert connection details
engine = sqlalchemy.create_engine('<YourConnection>')

# insert statement with variable format coding in VALUES
add_client = (
    'INSERT INTO server'
    ' (username, ipadress, blacklisted, clientid )'
    ' VALUES ( %s, %s, %s, %s)')

# invent some client data
username_s = 'Mary'
ipadress_s = '321.45.67.89'
BLACKLISTED_s = True
clientid_s = 123456
client_data = (username_s, ipadress_s, BLACKLISTED_s, clientid_s)

with engine.connect() as cnx:
    cnx.execute(add_client, client_data)