将数据而不是drop table插入mysql

时间:2013-10-07 16:03:49

标签: python mysql sql-insert sql-drop

我正在尝试获取一个python脚本来将数据插入到数据库中而不首先丢弃表..我确定这不难做但我似乎无法正确获取代码。 。 这是完整的python脚本..

#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import hashlib
import time
import MySQLdb


#Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this file

sensorids = ["28-000004944b63", "28-000004c01b2c"] 
avgtemperatures = []
for sensor in range(len(sensorids)):
        temperatures = []
        for polltime in range(0,3):
                text = '';
                while text.split("\n")[0].find("YES") == -1:
                        # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
                        tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave")
                        # Read all of the text in the file.
                        text = tfile.read()
                        # Close the file now that the text has been read.
                        tfile.close()
                        time.sleep(1)

                # Split the text with new lines (\n) and select the second line.
                secondline = text.split("\n")[1]
                # Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
                temperaturedata = secondline.split(" ")[9]
                # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
                temperature = float(temperaturedata[2:])
                # Put the decimal point in the right place and display it.
                temperatures.append(temperature / 1000 * 9.0 / 5.0 + 32.0)

        avgtemperatures.append(sum(temperatures) / float(len(temperatures)))

print avgtemperatures[0]
print avgtemperatures[1]

 #connect to db
db = MySQLdb.connect("localhost","user","password","temps" )

 #setup cursor
cursor = db.cursor()

 #create temps table
cursor.execute("DROP TABLE IF EXISTS temps")


sql = """CREATE TABLE temps (
      temp1 FLOAT,  
      temp2 FLOAT )"""
cursor.execute(sql)


 #insert to table
try:
    cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
    db.commit()
except:     
    db.rollback()


 #show table
cursor.execute("""SELECT * FROM temps;""")

print cursor.fetchall()
((188L, 90L),)

db.close()

这是我需要帮助的部分..

如果我让它删除表它工作正常但我不希望它删除表,只是将新数据插入到同一个表中。

 #connect to db
db = MySQLdb.connect("localhost","user","pasword1","temps" )

 #setup cursor
cursor = db.cursor()

 #create temps table
cursor.execute("DROP TABLE IF EXISTS temps")


sql = """CREATE TABLE temps (
      temp1 FLOAT,  
      temp2 FLOAT )"""
cursor.execute(sql)


 #insert to table
try:
    cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
    db.commit()
except:     
    db.rollback()


 #show table
cursor.execute("""SELECT * FROM temps;""")

print cursor.fetchall()
((188L, 90L),)

db.close()

2 个答案:

答案 0 :(得分:0)

每次要输入数据时都不必丢弃表格。实际上,它会破坏数据库的整个目的,因为每次运行脚本时都会删除所有以前的数据。

您应该要求创建表,但前提是它不存在。使用以下内容。

sql = """CREATE TABLE IF NOT EXISTS temps (
  temp1 FLOAT,  
  temp2 FLOAT )"""
cursor.execute(sql)

答案 1 :(得分:0)

我在更新方面遇到了这个问题。尝试将COMMIT添加到sql的末尾。我使用psycopg2连接到postgresql数据库。这是一个例子。

def simple_insert():
sql = '''INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); COMMIT;'''
try:
    conn = psycopg2.connect(database)                
    cur = conn.cursor()
    cur.execute(sql)
except:
    raise

我认为您的问题是您没有保存事务,而COMMIT命令应该修复它。