2017-06-03 115 views
0

我的表天氣Pymysql插入外鍵錯誤

create table weather (
      time timestamp default current_timestamp on update current_timestamp, 
      id smallint, 
      tpr float(3,1), 
      wet float(3,1), 
      uv tinyint(2), 
      foreign key (id) references database.station(pk)); 

表站

CREATE TABLE station(
pk SMALLINT(5) NOT NULL AUTO_INCREMENT, 
name VARCHAR(5), 
lng DOUBLE(10,6), 
lat DOUBLE(10,6), 
PRIMARY KEY(pk)); 

當我使用pymysql的id插入到天氣。

我做了兩個函數如下:

conn = pymysql.connect()#ignore the details 
def get_id_from_station(): 
    sql = """SELECT pk FROM station """ 
    conn.cursor().execute(sql) 
    id = conn.cursor().fetchone()[0] 
    weather_saved(id) 

def weather_saved(id): 
    #get the time,tpr,wet,uv value 
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)""" 
    db.execute(sql, (time, id,tpr, wet, uv)) 

但天氣表未更新。

什麼問題?

回答

0

這是更新天氣表的代碼。我使用Python 2.7,但它應該是相同的。我認爲你的問題可能是你沒有提交插入。

import pymysql 

conn = pymysql.connect(...) 

def get_id_from_station(): 
    sql = """SELECT pk FROM station """ 

    cursor = conn.cursor() 
    cursor.execute(sql) 
    row = cursor.fetchone() 
    weather_saved(row) 

import time 
import datetime 

def weather_saved(id): 
    #get the time,tpr,wet,uv value 
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)""" 
    cursor = conn.cursor() 
    ts = time.time() 
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 
    cursor.execute(sql, (timestamp, id,7, 7, 7)) 
    conn.commit() 

get_id_from_station()