python - SQL与python连接

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

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

我的代码的问题是,如果我将字段名称添加到 concat 函数,例如 seq=concat(seq, %s) 我会收到 SQL 语法错误,但是当我添加字段时name 作为一个变量,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)

最佳答案

我认为你想要:

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

这会将每个新行附加到 seq 列中现有数据库值的末尾。

关于python - SQL与python连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58685518/

相关文章:

php - 如果其他条件不起作用

php - 为什么这不是从 7 天前提取数据?

python - 在 Python 3.6 : isinstance vs. 中解释 ASTs monkey-patching vs. visit_NodeType vs. macros?

python-3.x - 如何传递/读取 PIL.JpegImagePlugin.JpegImageFile 对象?

python - 如何在python中停止udp套接字线程?

python - 使用 Postgresql 数据库创建 Azure Web 应用程序(这可能吗?)

MySQL:对存储过程参数使用选择语句

Python 帮助 .Join 给出语法错误

python - dedent 函数在 Matplotlib 3.1 中已弃用,将在 3.3 中删除

python - 从 python 列表中选择子列表,在同一元素上开始和结束