如何在sqlite3 python中按行和列插入和调用
假设我有一个简单的x行和y列数组,其中包含相应的值, 做这三件事的最佳方法是什么? 如何插入、更新特定行和列的值?如何为每行和每列选择一个值如何在sqlite3 python中按行和列插入和调用,python,sqlite,Python,Sqlite,假设我有一个简单的x行和y列数组,其中包含相应的值, 做这三件事的最佳方法是什么? 如何插入、更新特定行和列的值?如何为每行和每列选择一个值 import sqlite3 con = sqlite3.connect('simple.db') c = con.cursor() c.execute('''create table simple (links text)''') con.commit() dic = {'x1':{'y1':1.0,'y2':0.0},'x2':{'y1':0.0,'
import sqlite3
con = sqlite3.connect('simple.db')
c = con.cursor()
c.execute('''create table simple (links text)''')
con.commit()
dic = {'x1':{'y1':1.0,'y2':0.0},'x2':{'y1':0.0,'y2':2.0,'y3':1.5},'x3':{'y2':2.0,'y3':1.5}}
ucols = {}
## my current thoughts are collect all row values and all column values from dic and populate table row and columns accordingly how to call by row and column i havn't figured out yet
##populate rows in first column
for row in dic:
print row
c.execute("""insert into simple ('links') values ('%s')"""%row)
con.commit()
##unique columns
for row in dic:
print row
for col in dic[row]:
print col
ucols[col]=dic[row][col]
##populate columns
for col in ucols:
print col
c.execute("alter table simple add column '%s' 'float'" % col)
con.commit()
#functions needed
##insert values into sql by row x and column y?how to do this e.g. x1 and y2 should put in 0.0
##I tried as follows didn't work
for row in dic:
for col in dic[row]:
val =dic[row][col]
c.execute("""update simple SET '%s' = '%f' WHERE 'links'='%s'"""%(col,val,row))
con.commit()
##update value at a specific row x and column y?
## select a value at a specific row x and column y?
因此,您有一个字典字典,希望将其转换为SQL表 我会采取的步骤
## update value at a specific row x and column y?
def set_cell(connection, x_name, y_name, value):
sql = 'UPDATE simple SET %s="%s" WHERE row_name="%s"' % (
y_name, value, x_name
)
connection.execute(sql)
## select a value at a specific row x and column y?
def get_cell(connection, x_name, y_name):
sql = 'SELECT %s FROM simple WHERE row_name="%s"' % (
y_name, x_name
)
# Return the first row of results (there should be only one)
# and the first column from that row
return list(connection.execute(sql))[0][0]
我很惊讶这没有因为在问题中添加“伟大的教程问题”而被否决。嗨,我是新来的,我会解决:)非常感谢你的详细回答,很高兴看到伟大的代码!很好,谢谢。如果有用的话,你介意接受我的答案吗?哦,你没看到,我试过投票,但还没有代表,哈哈,还有一个问题我正在努力解决,我应该把这个作为另一个答案吗?如果我将dict中的列值更改为“y3”或“some random string”,则代码无法正常工作。我尝试过改变一些东西,而不是使用真实的文本,但是当我调用它时,它说该列不存在任何想法?不要紧:),刚才看到sql='选择%s对于字符串需要是“%s”,讨厌的sql及其敏感的语法。请注意,当您不能信任数据时,不应使用此解决方案。检查pydocs的sqlinjection
## update value at a specific row x and column y?
def set_cell(connection, x_name, y_name, value):
sql = 'UPDATE simple SET %s="%s" WHERE row_name="%s"' % (
y_name, value, x_name
)
connection.execute(sql)
## select a value at a specific row x and column y?
def get_cell(connection, x_name, y_name):
sql = 'SELECT %s FROM simple WHERE row_name="%s"' % (
y_name, x_name
)
# Return the first row of results (there should be only one)
# and the first column from that row
return list(connection.execute(sql))[0][0]