与python串联的SQL

我正在尝试使用串联更新mysql数据库字段。我必须逐行读取文件,并且需要在已加载的行后附加现有字符串。我必须这样做,因为我的目标是将3gb长的空格分隔的文本文件插入一个longtext字段,而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)
jintiansheng 回答:与python串联的SQL

我认为您想要

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

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

本文链接:https://www.f2er.com/3169769.html

大家都在问