Database 在数据库中创建多行
我不知道为什么我不能测试我的功能。我想要的输出是ID,然后是Room,但如果同一ID有多个房间,则将其放入新行,如Database 在数据库中创建多行,database,python-3.x,Database,Python 3.x,我不知道为什么我不能测试我的功能。我想要的输出是ID,然后是Room,但如果同一ID有多个房间,则将其放入新行,如 ID Room 1 SW128 SW 143 into ID Room 1 SW128 1 SW143 这是文件中的一些数据 1,SW128,SW143 2,SW309 3,AA205 4,AA112,SY110 5,AC223 6,AA112,AA206 但我甚至不能测试我的功能。谁能帮我修一下吗
ID Room
1 SW128 SW 143
into
ID Room
1 SW128
1 SW143
这是文件中的一些数据
1,SW128,SW143
2,SW309
3,AA205
4,AA112,SY110
5,AC223
6,AA112,AA206
但我甚至不能测试我的功能。谁能帮我修一下吗
def create_location_table(db, loc_file):
'''Location table has format ID, Room'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Locations''')
# create the table
cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')
# Add the rows
loc_file = open('locations.csv', 'r')
loc_file.readline()
for line in loc_file:
d = {}
data = line.split(',')
ID = data[0]
Room = data[1:]
for (ID, Room) in d.items():
if Room not in d:
d[ID] = [Room]
for i in Rooms:
cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (ID,
Room))
# commit and close cursor and connection
con.commit()
cur.close()
con.close()
问题是,
d
始终是一个空的dict,因此d.items()中(ID,Room)的不会做任何事情。您需要做的是在房间
上循环。而且您不需要d
dict
def create_location_table(db, loc_file):
'''Location table has format ID, Room'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Locations''')
# create the table
cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')
# open the CSV
csv_content = open(loc_file, 'r')
for line in csv_content:
data = line.strip().split(',')
# made lowercase following PEP8, but 'id' is a built in name in python
idx = data[0]
rooms = data[1:]
# loop through the rooms of this line and insert one row per room
for room in rooms:
cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (idx, room))
# for debug purposes only
print('INSERT INTO Locations VALUES(%s, %s)' % (idx, room))
# commit and close cursor and connection
con.commit()
cur.close()
con.close()
# call the method
create_location_table('db.sqlite3', 'locations.csv')
注意:下面我将您的变量设置为小写
编辑:发布完整代码示例,使用loc_文件
参数注释不用于扩展讨论;这段对话已经结束。