【问题标题】:SQL concatenating with pythonSQL与python连接
【发布时间】:2020-07-28 07:44:36
【问题描述】:

我正在尝试使用串联更新我的 mysql 数据库字段。我必须逐行读取文件,并且需要将现有字符串附加到加载的行。我必须这样做,因为我的目标是在一个长文本字段中插入一个 3gb 长的空格分隔的文本文件,而 mysql 只能处理要插入的 1gb 文本。

我的代码的问题是,如果我将字段名称添加到 seq=concat(seq, %s) 这样的 concat 函数中,我会收到 SQL 语法错误,但是当我将字段名称添加为变量时,python 就像它是一个字符串一样。

这个输入文件很长:

aaa
bbb
ccc

我想要一个更新的 mysql 字段,如下所示: aaabbbccc

但我明白了:seqccc

知道我应该如何使用字段名来完成这项工作吗?

import mysql.connector

connection = mysql.connector.connect(host='localhost',
                                         database='sys',
                                         user='Pannka',
                                         password='???')

cursor = connection.cursor()
with open('test.txt', 'r') as f:
    for line in f:
        sql = "update linedna set seq=concat(%s, %s) where id=1"
        val=('seq', line.rstrip())
        print(line.rstrip())
        cursor.execute(sql, val)
        connection.commit()

cursor.close()
connection.close()
f.close()
print(0)

【问题讨论】:

  • 参数化用于字符串文字而不是标识符,例如表或列名。

标签: python mysql python-3.x database sql-update


【解决方案1】:

我认为你想要:

sql = "update linedna set seq = concat(seq, %s) where id=1"
val=(line.rstrip())
cursor.execute(sql, val)
connection.commit()

这将在seq 列中已存在的数据库值的末尾追加每个新行。

【讨论】:

  • 是的,这正是我想要做的,但它给了我一个 sql 语法错误。 Traceback: cursor.execute(sql, val) (...) mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s) where id=1' at line 1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2020-03-30
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
相关资源
最近更新 更多