python - 插入数据而不是删除表到mysql

标签 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()

最佳答案

您不必在每次要输入数据时都删除表格。事实上,它违背了数据库的全部目的,因为每次运行脚本时都会删除所有以前的数据。

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

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

关于python - 插入数据而不是删除表到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19229463/

相关文章:

sql - 根据列值插入 x 行

python - 在 GLUE 任务上微调 BERT 时,如何监控训练和评估损失?

sql - Mysql高级语句

mysql - 如何检查 "SHOW profiles"上的 "Source Distribution"之类的 MySQL 查询时间?

php - 类别产品重新索引在 magento 1.8 中不起作用

sql - Hadoop/Hive-将单行拆分为多行并存储到新表中

mysql - INSERT 期间的 MSSQL 格式日期和时间

python - QListView 中自定义 IndexWidget 的平滑延迟加载和卸载

python - 无法在 us-central1 中更新加密 key

python - 如何单步执行 Ipython 中的 help() 文本?