无法使用带有 mariadb 连接器的 Set 子句插入字符串 (python)

Cannot INSERT strings with Set Clause with mariadb connector (python)

我想使用 python-mariadb 连接器在我的 table 中插入一个新行。为此,我更喜欢使用 SET 子句。 出于某种原因,如果我只想保存整数(即 y=2),它确实有效,但是当我使用字符串时,会出现以下错误

Unknown column 'myString' in 'field list'

好像把字符串的内容当成了列名?知道如何解决这个问题(我可以用 INSERT INTO ... VALUES ... 做到这一点,但我想在这里使用 SET 子句)。据我了解,它应该同时保存 int 和 str 而不会引发错误 谢谢。

参见下面的代码示例

def myfunction():
    x = 1
    y ='myString'
    db = connect_db()
    cur = db.cursor()
    sql = "INSERT INTO Table SET col1={}, col2={}"
    cur.execute(sql.format(x, y))
    db.commit()
    db.close()
    return

这里是 MariaDB 连接器,但这应该没问题,因为它适用于其他数据库功能。

import mariadb

def connect_db():
    db = mariadb.connect(
        user="user",
        password="123",
        host="localhost",
        port=3306,
    database="DB"
    )
db.autocommit = False
return db

您没有使用正确的插入语法

sql = "INSERT INTO Table (col1,col2) values({}, {})"

但如果您想更新现有行:

sql = "UPDATE Table SET col1={}, col2={} WHERE id = {}"

您可能需要一个 where 子句

相关代码生成 SQL 语句:

INSERT INTO Table SET col1=1, col2=myString;

这是不正确的语法,字符串必须用单引号引起来:

INSERT INTO Table (col1, col2) VALUES (1, 'myString');
def myfunction():
    x = 1
    y ='myString'
    db = connect_db()
    cur = db.cursor()
    sql = "INSERT INTO Table (col1, COL2) VALUES ({}, '{}')"
    cur.execute(sql.format(x, y))
    db.commit()
    db.close()
    return

但以上是脆弱的。不要使用字符串构建方法来创建 SQL 语句,使用参数绑定要好得多。

def myfunction():
    x = 1
    y ='myString'
    db = connect_db()
    cur = db.cursor()
    sql = "INSERT INTO Table (col1, col2) VALUES (?, ?)"
    cur.execute(sql, (x, y))
    db.commit()
    db.close()
    return

MariaDB 连接器 documentation 解释了这些事情。

Retrieving Data

Once you have the initial code in place you can start working with the data. The first thing you should do is try to retrieve information from the database. Here is code for a query against the employees database:

cur.execute(
    "SELECT first_name,last_name FROM employees WHERE first_name=?", 
    (some_name,)) 

MariaDB Connector/Python uses prepared statements, sanitizing and inserting the values from the tuple into the position of the question marks (?). This is safer than inserting through f-strings or format specifiers when working with user provided information.

The query results are stored in a list in the cursor object. To view the results, you can loop over the cursor.

Adding Data

Using the same execute() method with an INSERT statement, you can add rows to the table.

cursor.execute(
    "INSERT INTO employees (first_name,last_name) VALUES (?, ?)", 
    (first_name, last_name))