【发布时间】: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