2010-04-22 3 views
1

x 행과 y 열에 해당 값이있는 간단한 배열이 있다고합시다. 3 가지 작업을 수행하는 가장 좋은 방법은 무엇입니까? 특정 행 열에 값을 삽입, 업데이트하는 방법은 무엇입니까? 각 행과 열에 대한 값을 선택하는 방법sqlite3 파이썬에 행과 열을 삽입하고 호출하는 방법

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

+0

안녕하세요, 저는 여기에서 새로운 것을 고쳐 드리겠습니다. – user291071

답변

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

+0

쿨, 고마워. 그것이 유용했다면 내 대답을 받아들이겠습니까? – Ian

+0

오, 나중에 그것을 보지 못했지만, 나는 upvoting을 시도했지만 아직 그것에 대한 담당자가 없어, 롤, 다른 질문으로 나는 다른 대답으로 넣어해야합니까? dict의 열 값을 변경하여 'y3'을 '임의의 문자열'이라고 말하면 코드가 작동하지 않습니다. 나는 텍스트를 사용하는 대신에 여러 가지를 바꾸려고 노력했다. 그러나 나는 그것을 호출 할 때 어떤 생각도 존재하지 않는다고 말한다. – user291071

관련 문제