【发布时间】:2021-01-08 02:35:38
【问题描述】:
错误:
Traceback(最近一次调用最后一次):文件“read_data_two.py”, 第 59 行,在 insertIntoTable(info, count) 文件“read_data_two.py”,第 42 和 43 行,在 insertIntoTable cursor.execute("INSERT INTO New_Packet VALUES (%s, %s, %s, %s, %s)", (local_time, IP_Protocol, src_address, dest_address, transport_protocol)) sqlite3.OperationalError: near "%": 语法错误
上下文:我正在编写一个代码,它将逐行从文件中读取。它将从文本文件中读取每一行。然后它将行拆分为一个列表,列表的每个索引将包含不同的属性(在这种情况下,属性将是有关数据包的信息(传输协议、src_address、dest_address、IP 协议和本地时间)。我当我尝试从列表中插入元素时出现错误。我尝试了多种方法,但是当我从列表中输入元素时,它实际上被读取为字符串。我尝试了 %s,但它现在导致错误% 符号。另外,我不明白为什么在调用 insertIntoTable() 函数时会出错。
1) import sqlite3 #Gives program access to the sqlite3 module
2)
3)
4)def insertIntoTable(info, count):
5) print(count)
6) #print(type(info))
7) local_time = info[0]
8) #print(local_time)
9) #print(type(local_time))
10) #print(info[0])
11)
12) IP_Protocol = info[1]
13) #print(type(IP_Protocol))
14) #print(info[1])
15)
16) src_address = info[2]
17) #print(info[2])
18)
19) dest_address = info[3]
20) #print(info[3x])
21)
22) transport_protocol = info[4]
23) #print(info[4])
24) #print(" ")
25)
26) connection = sqlite3.connect("PacketInfo.db") #sqlite3.cnnect() function returns objects 27) #that will be used to interact with database
28) cursor = connection.cursor() #creates cursor object used to SQL statements to a SQLite
29)
30)
31) #if count == 0:
32) if count == 0:
33) cursor.execute("CREATE TABLE IF NOT EXISTS New_Packet (local_time VARCHAR , IP_Protocol 34) VARCHAR, src_address VARCHAR, dest_address VARCHAR, transport_protocol VARCHAR)")
35) connection.commit()
36) count += 1
37) #count += 1
38)
39) #print(count)
40) #cursor.execute(f "INSERT INTO table VALUES {local_time}, {IP_Protocol}, {src_address},
41){dest_address}, {transport_protocol},")
42) cursor.execute("INSERT INTO New_Packet VALUES (%s, %s, %s, %s, %s)", (local_time,
43) IP_Protocol, src_address, dest_address, transport_protocol))
44) connection.commit()
45) rows = cursor.execute("SELECT* FROM New_Packet").fetchall() #fetchall() retrieves all the
46) connection.commit()
47) #print("Made it")
48) print(rows)
49) cursor.close()
50) return
51)file = open("packets.txt","r")
52)list_of_info = []
53)count = 0
54)for line in file.readlines():
55) if not line:
56) break
57) info = line.split()
58) print(info)
59) insertIntoTable(info, count)
【问题讨论】: