2010-04-22 152 views
1

可以說我有一個簡單的x行和y列與相應的值的數組, 做3件事情的最佳方法是什麼? 如何插入,更新特定行列的值?如何爲每一行和列選擇一個值,如何插入和調用行和列到sqlite3 python

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? 
+0

我很驚訝這還沒有downvoted添加 「偉大的教程問題」 來這個問題。 – mikerobi 2010-04-23 03:25:08

+0

嗨,我是新來的,我會修復:) – user291071 2010-04-23 05:18:16

回答

2

因此,你有一個字典的字典,你想轉換成一個SQL表。

步驟我會拿

  1. 找到你需要的列。
  2. 創建表模式。
  3. 循環遍歷每一行。
    1. 編譯每列的值的集合。
    2. 插入它。

所以:

import sqlite3 
con = sqlite3.connect('simple.db') 
c = con.cursor() 

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} 
    } 

# 1. Find the unique column names. 
columns = set() 
for cols in dic.values(): 
    for key in cols: 
     columns.add(key) 

# 2. Create the schema. 
col_defs = [ 
    # Start with the column for our key name 
    '"row_name" VARCHAR(2) NOT NULL PRIMARY KEY' 
    ] 
for column in columns: 
    col_defs.append('"%s" REAL NULL' % column) 
schema = "CREATE TABLE simple (%s);" % ",".join(col_defs) 
c.execute(schema) 

# 3. Loop through each row 
for row_name, cols in dic.items(): 

    # Compile the data we have for this row. 
    col_names = cols.keys() 
    col_values = [str(val) for val in cols.values()] 

    # Insert it. 
    sql = 'INSERT INTO simple ("row_name", "%s") VALUES ("%s", "%s");' % (
     '","'.join(col_names), 
     row_name, 
     '","'.join(col_values) 
     ) 
    c.execute(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] 
+0

非常感謝您的詳細的答案,很高興看到偉大的代碼! – user291071 2010-04-23 05:16:59

+0

很酷,謝謝。如果它有用,你會介意接受我的答案嗎? – Ian 2010-04-23 15:07:55

+0

哦,你沒有看到它,我嘗試upvoting,但沒有代表呢,大聲笑,我正在努力的另一個問題,我應該把這作爲另一個答案?如果我改變字典中的列值讓'y3'變成'一些隨機字符串',我無法讓代碼工作。我嘗試改變幾件事情,而不是使用真正的我用過的文本,但是當我打電話時說該列不存在任何想法? – user291071 2010-04-23 17:42:34