Question

I'm attempting to get a python script to insert data into a database without having it drop the table first.. I'm sure this isn't hard to do but I can't seem to get the code right.. Here is the full python script..

#!/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()

This is the part I need assistance with..

If I have it drop the table it works fine but I don't want it to drop the table, just insert the new data into the same table.

 #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()
Was it helpful?

Solution

You shouldn`t have to drop a table each time you want to enter data. In fact, it defeats the whole purpose of the database since you will remove all the previous data each time you run your script.

You should ask to create the table but only if it does not exists. Use the following.

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

OTHER TIPS

I've had this problem with updating. Try adding COMMIT to the end of your sql. I use psycopg2 to connect to a postgresql database. Here is an example.

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

I think your problem is your not saving the transaction and the COMMIT command should fix it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top