2014-01-13 45 views
2

嗨,我是新來的Python和SQLite和我只是測試一個簡單的編碼如下 進口sqlite3的SQLite數據庫不存儲以前的數據插入

os.chdir("C:\Backup") 
conn = sqlite3.connect('FBG.db') 
c=conn.cursor() 
c.execute('''create table if not exists A (time INTEGER PRIMARY KEY, data REAL)''') 
data=(1,2) 
c.execute("insert into A (time, data) values (?,?)", data) 

c.execute('SELECT * FROM A ORDER BY time').fetchall() 

c.close() 

所以問題是每一次,我運行代碼,我假設它將存儲前面的數據,數據庫列表將變得更大,但是發生了什麼事,無論我運行了多少次,該表中的所有數據仍然是(1,2),而我儘管應該是很多(1,2)。所以我想知道這是什麼原因?因爲對我來說,它與「插入」或「插入或替換」沒有任何區別。

編輯:

with open(file, 'rb') as f: 
     entries = csv.reader(f,delimiter='\t') 
     rows= list(entries) 
    ###  
    # For first point (A) three strain values and temperature 
    ### 

    ###use numpy to turn the csv files into a matrix 
     matrix= numpy.array([]) 
     for i in range (1,5) : #in the setted files using len(list(rows)) to make it read all the coloumn and create a new table for each different coloumn 
      a=list(rows[3]) 
      result = [0,0] 
    # the program will detect the number and name for each coloumn then show add new table untill there's no more coloumn left 
      for r in range(5,len(rows)): 
       data=list(rows[r]) 
       c.execute("create table if not exists " + str(a[i]) + file[0:4] + file[4:6] + " (time real, data real)") # NEED TO CHANGE TABLE NAME FROM A TO B OR C OR ETC 
       matrix=numpy.append(matrix,float(data[0])) 
       matrix=numpy.append(matrix,float(data[i])) 
       result= numpy.vstack((result,matrix)) 
       matrix=[] 
    # create a sqlite table named by its point in this case is A with different name to the coloumn 
       result = numpy.delete(result, (0), axis=0) 
       for item in result: 
        c.execute("insert into " + str(a[i]) + file[0:4] + file[4:6] + " values (?,?)", item) 
+1

您不能有兩個具有相同主鍵的記錄。 (在嘗試插入副本時應該會收到錯誤消息。) –

回答

1

像@CL是說你不能有2條記錄與同PRIMARY KEY

此表應與3列建。

  1. A_ID PRIMARY KEY自動遞增NOT NULL
  2. time DATETIME(可能NOT NULL以及
  3. data REAL

換句話說,一定不要將你的代碼的主鍵,讓數據庫爲你自動增加它,或者使用GUID。

此行

data=(1,2) 

是被插入到你的數據庫的唯一的事。因此數據庫中唯一的記錄將是您插入的記錄,即1,2

+0

但我已經運行了幾次程序,我認爲這意味着要將數據=(1,2)添加到同一個數據庫,所以它應該有多個數據它?當我向表中添加數據時,我使用了類似的代碼,我在代碼中附加了代碼,在這種情況下,代碼只是在數據庫中添加任何數據,而不管它是否重複。我試圖找出原因。 –

+0

在你動態添加新行的代碼塊中,它們永遠不會相同。並且您不試圖設置該行的主鍵。該代碼每次創建一個新表並創建一個新行,因此看起來好像有一堆表,每行都有一行 – Malachi

+0

仍試圖找出爲什麼兩個代碼中的「插入」會給出不同的結果。但是,無論如何感謝:) –