如何使用Python将值写入SQLite中选定的行和列

如何使用Python将值写入SQLite中选定的行和列,python,database,python-3.x,sqlite,Python,Database,Python 3.x,Sqlite,因此,我目前正在尝试使用SQLite数据库,并希望获得一些关于将值写入数据库的特定行和列(So单元格)的最佳方法的输入。我知道如何逐行写入数据库,因此基本上每次都会在数据库的末尾追加一行,但我希望不按顺序将数据写入数据库 我在下面列出了一个任意的例子来说明我试图用苹果做什么。在本例中,我在一个数据库中创建了两个表。第一个表将是我的ID表,称为苹果。这将包含一个主键和两列,分别表示苹果名称和种植它的农场。第二个table keyFeatures将再次包含主键,该主键引用apple table中苹果

因此,我目前正在尝试使用SQLite数据库,并希望获得一些关于将值写入数据库的特定行和列(So单元格)的最佳方法的输入。我知道如何逐行写入数据库,因此基本上每次都会在数据库的末尾追加一行,但我希望不按顺序将数据写入数据库

我在下面列出了一个任意的例子来说明我试图用苹果做什么。在本例中,我在一个数据库中创建了两个表。第一个表将是我的ID表,称为苹果。这将包含一个主键和两列,分别表示苹果名称和种植它的农场。第二个table keyFeatures将再次包含主键,该主键引用apple table中苹果的ID,但也包含一列,用于说明味道、纹理和颜色

在下面的例子中,我只有来自农场3的苹果粉女士的味道、质地和颜色。现在,我想在填充任何其他行之前,将该信息写入相关列中表keyFeature的第3行。为了我的生命,我不知道该怎么做。我假设我需要将光标定位到正确的行,但是从文档中我不清楚如何实现这一点。我相信这是一个微不足道的问题,如果有人能给我指出正确的方向,我将不胜感激

import sqlite3

dbName = 'test.db'

################# Create the Database File ###################

# Connecting to the database file
conn = sqlite3.connect(dbName)
c = conn.cursor()

#Create the identification table with names and origin
c.execute('''CREATE TABLE apples(appleID INT PRIMARY KEY, Name TEXT, 
farmGrown TEXT)''')

#Create the table with key data
c.execute('''CREATE TABLE keyFeature(appleID INT PRIMARY KEY, taste INT, 
texture INT, Colour TEXT)''')

#Populate apples table and id in keyFeature table
AppleName = ['Granny Smith', 'Golden Delicious', 'Pink Lady', 'Russet']
appleFarmGrown = ['Farm 1', 'Farm 2', 'Farm 3', 'Farm 4']
id = []

for i in range(len(AppleName)):
    id.append(i+1)
    c = conn.cursor()
    c.execute('''INSERT INTO apples(appleID, Name, farmGrown)
                    VALUES(?,?,?)''', (id[i], AppleName[i], appleFarmGrown[i]))

    c.execute('''INSERT INTO keyFeature(appleID)
                    VALUES(?)''', (id[i],))


#Current Apple to populate row in keyFeature
appleCurrent = (('Pink Lady','Farm 3')) 

tasteCurrent = 4
textureCurrent = 5
colourCurrent = 'red'

#Find ID and write into the database

c.execute("SELECT appleID FROM apples")
appleIDDB = c.fetchall()

c.execute("SELECT name FROM apples")
nameDB = c.fetchall()

c.execute("SELECT farmGrown FROM apples")
farmGrownDB = c.fetchall()

conn.commit()
conn.close()


# I assume that if I close the connection the cursor whould be positioned at the 
# first row again but this doesn't appear to be the case
conn = sqlite3.connect(dbName)

for i in range(len(appleIDDB)):
    c = conn.cursor()

    if ((nameDB[i][0] == appleCurrent[0]) and (farmGrownDB[i][0] == appleCurrent[1])):
        idCurrent = appleIDDB[i][0]
        print("This apple matches the apple stored with id number " +str(idCurrent))
        # This writes into the fifth row of the table
        c.execute('''INSERT INTO keyFeature(taste, texture, Colour)   
                   VALUES(?,?,?)''', (tasteCurrent, textureCurrent, colourCurrent))

conn.commit()
conn.close()
你快到了

像sqlite这样的应用程序不太像speadsheet中的表。与按特定顺序排列的行列表不同,您只需要“一大袋行”(技术上称为一组元组),您可以按任何方式对它们进行排序

正如您在创建表时已经确定的那样,我们解决问题的方法是确保每一行都有一个允许我们识别它的键(如您的apple ID)。当我们希望这个键在另一个表中表示一个ID时,这称为。因此,我们只需要将外键(称为
appleID
)添加到
keyFeature
表中,并在添加行时使用它

首先,从你的第一个for循环中去掉这个,我们在这个阶段不需要它,桌子可以空着

c.execute('''INSERT INTO keyFeature(appleID)
                VALUES(?)''', (id[i],))
接下来,你不需要整张桌子就能找到你想要的苹果,你只需选择你感兴趣的一个:

c.execute("SELECT appleID FROM apples WHERE name=? AND farm=?",("Pink Lady", "Farm 3"))
idCurrent = c.fetchone()[0]
真正的诀窍是,当向
keyFeature
添加数据时,我们必须将所有数据插入一条语句中。通过这种方式,一次使用ID和所有其他信息创建一个新的元组(行)。好像它在桌子上的“正确位置”

c.execute('''INSERT INTO keyFeature(appleID, taste, texture, Colour)   
                   VALUES(?,?,?,?)''', (idCurrent, tasteCurrent, textureCurrent, colourCurrent))
现在我们可以使用我们感兴趣的苹果的ID从keyFeature表中检索信息

c.execute("SELECT taste, texture, Colour FROM keyFeature WHERE apple_id=?", (my_apple_id,))
最终完整代码:

import sqlite3

dbName = 'test.db'

################# Create the Database File ###################

# Connecting to the database file
conn = sqlite3.connect(dbName)
c = conn.cursor()

#Create the identification table with names and origin
c.execute('''CREATE TABLE apples(appleID INT PRIMARY KEY, Name TEXT, 
farmGrown TEXT)''')

#Create the table with key data
c.execute('''CREATE TABLE keyFeature(appleID INT PRIMARY KEY, taste INT, 
texture INT, Colour TEXT)''')

#Populate apples table and id in keyFeature table
AppleName = ['Granny Smith', 'Golden Delicious', 'Pink Lady', 'Russet']
appleFarmGrown = ['Farm 1', 'Farm 2', 'Farm 3', 'Farm 4']
id = []

for i in range(len(AppleName)):
    id.append(i+1)
    c = conn.cursor()
    c.execute('''INSERT INTO apples(appleID, Name, farmGrown)
                    VALUES(?,?,?)''', (id[i], AppleName[i], appleFarmGrown[i]))

#Current Apple to populate row in keyFeature
appleCurrent = ('Pink Lady','Farm 3')

tasteCurrent = 4
textureCurrent = 5
colourCurrent = 'red'

#Find ID and write into the database
c.execute("SELECT appleID FROM apples WHERE name=? AND farm=?",(appleCurrent[0], appleCurrent[1]))
idCurrent = c.fetchone()[0]

c.execute('''INSERT INTO keyFeature(appleID, taste, texture, Colour)   
                       VALUES(?,?,?,?)''', (idCurrent, tasteCurrent, textureCurrent, colourCurrent))

conn.commit()
conn.close()