Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将txt文件中的数据插入数据库_Python - Fatal编程技术网

Python 将txt文件中的数据插入数据库

Python 将txt文件中的数据插入数据库,python,Python,我正在尝试将一个txt文件中的所有行以格式名称:age分别插入数据库 这就是我尝试过的: with open('test.txt') as f: reader = csv.reader(f) for row in reader: mycursor.execute("INSERT INTO test (name, age) VALUES (%s, %s)") Txt文件: Adam:23 Olivia:19 Mark:45 Robert:34

我正在尝试将一个txt文件中的所有行以格式名称:age分别插入数据库

这就是我尝试过的:

with open('test.txt') as f:
    reader = csv.reader(f)
    for row in reader:
        mycursor.execute("INSERT INTO test (name, age) VALUES (%s, %s)")
Txt文件:

Adam:23
Olivia:19
Mark:45
Robert:34
Markus:23

请帮我弄清楚,或者至少给我一个提示,我是编程新手。

您的代码很好,您只需要在查询中插入
值元组

agefile = open("text.txt", "r")


sql = "INSERT INTO test (nick, ip) VALUES (%s, %s)"

for row in agefile:
    data = row.split(':')
    val = (data[0], data[1])
    mycursor.execute(sql, val)

agefile.close()
mycursor.execute("INSERT INTO test (name, age) VALUES (%s, %s)" %tuple(row.split(':'))
或者

如果将查询与数据分开,效果会更好

query=“插入测试(名称、年龄)值(%s,%s)”
将open('test.txt')作为f:
读卡器=csv。读卡器(f)
对于读取器中的行:
mycursor.execute(查询,%tuple(row.split(':'))

那么,你的问题是什么?如果你能帮助我:)谢谢!它可以工作,但当我在数据库中检查它时,它的结尾包含“\n”('1.1.1.1\n')@NataliaBarzowinska将删除代码中结尾的
\n
,而不是
数据[1]
使用
数据[1].rstrip()
。感谢您的帮助,它现在工作得很好