繁体   English   中英

如何使用Python在SQL中插入或更新

[英]How to Insert or Update in SQL using Python

我在python中有一个列表,当前正在插入一个名为SocketTest的SQL表中。 基本上,我存储连接日志。 我只想存储某人连接的最后一个位置AP(接入点),而不是像我现在这样存储它们的列表。 它们按时间顺序读取并通过套接字,因此我在函数中获得的最新列表始终是该用户的最新列表。 基本上,我的程序从套接字读取数据,并创建一个列表,其中包含用逗号分隔的信息,然后将其插入到表中,而当套接字中仍然有信息时,它会不断重复。 我在名为i的列表。 我一直在尝试自己解决这个问题,但我没有经验。 我想查看作为ID的PK,如果尚未存储ID,则插入该行;如果ID已经存在,则替换或更新存储的行。 我一直在寻找替换并在重复键上插入,但无法正常工作。 感谢您的帮助,代码如下。

SocketTest是表:PK是ID:Pringle是示例行:

编辑:我正在导入MYSQLDB作为mdb

def ParseArray(l): #parses line in socke
i.append(l.split()[+0] + '')  # Gets Day
i.append(l.split()[+1] + '')  # Gets Month
i.append(l.split()[+3] + '')  # Gets Year
i.append(l.split()[+2] + '')  # Gets Time
i.append(l.split()[-2] + '')  # Gets Device
i.append(l.split()[+9] + '')  # Gets  ID
i.append(l.split()[+18] + '')  # Gets AP
i.append(l.split()[+19] + '')  # Gets AP Group
i.append(l.split()[+16] + '/n')  # Gets MAC
#insert line into db else by primary key (ID)
#update line to db if ID doesn't exist
#pringle = ['Dec', '11', '2018', '15:10:51', 'iPhone', '[jeref2]', 
#    'home', 'hm1', '45.88.34.58)\n']


sql = "INSERT INTO SocketTest (month, day, year, time, device, Id, ap, 
    ApGroup, MacAdd) VALUES ('%s');" % "', '".join(i)
cur.execute(sql)
con.commit()

编辑:其余代码

#!/bin/python

import socket
import os, os.path
import MySQLdb as mdb
con = mdb.connect('x', 'x', 'x', 'x');
cur = con.cursor()



#pringle=['Dec', '11', '2018', '15:10:51', 'iPhone', '[josheer]', 'FRD', 'BHJ', '45.33.88.34)\n']














def ParseArray(l): #parses line in socke
i.append(l.split()[+0] + '')  # Gets Day
i.append(l.split()[+1] + '')  # Gets Month
i.append(l.split()[+3] + '')  # Gets Year
i.append(l.split()[+2] + '')  # Gets Time
i.append(l.split()[-2] + '')  # Gets Device
i.append(l.split()[+9] + '')  # Gets  ID
i.append(l.split()[+18] + '')  # Gets AP
i.append(l.split()[+19] + '')  # Gets AP Group
i.append(l.split()[+16] + '/n')  # Gets MAC

try:
    row_to_insert = [val1, val2, val3]
    cur.execute("INSERT INTO SocketTest (month, day, year, time, device,Id, ap, ApGroup, MacAdd) VALUES(%s, %s, %s)",
                   (i)

except: pymysql.IntegrityError:
    cur.execute("""UPDATE SocketTest
    SET column2 = {1}, column3 = {2}
    WHERE column1 = {0}
    """.format(val1, val2, val3)







#sql = "REPLACE INTO SocketTest (month, day, year, time, device,Id, ap, ApGroup, MacAdd) VALUES ('%s');" % "', '".join(
    #i)
#cur.execute(sql)
#con.commit()





con.commit()








print(i)

del i[:]



i = []

if os.path.exists("/home/log/x"):
os.remove("/home/log/x")

sock = socket.socket(x, sx)
sock.bind("/home/log/xt")
infile = sock.makefile('r')




while True:
    l = sock.recv(4096).decode()
    ParseArray(l)

如果您使用的是pymysql库,则可以执行以下操作:

row_to_insert = [val1, val2, val3]

cursor.execute("INSERT INTO my_table_name (column1, column2, column3) VALUES(%s, %s, %s)", 
    row_to_insert)

更多信息可以在这里找到: 如何在Python的SQL语句中使用变量?

海报评论后编辑:

try:
    row_to_insert = [val1, val2, val3]
    cursor.execute("INSERT INTO my_table_name (column1, column2, column3) VALUES(%s, %s, %s)",
                   row_to_insert)

except pymysql.IntegrityError:
    cursor.execute("""UPDATE my_table_name 
    SET column2 = {1}, column3 = {2}
    WHERE column1 = {0}
    """.format(val1, val2, val3)

我会将您的函数重写为:

def ParseArray(l): #parses line in socke
  day = (l.split()[+0] + '')  # Gets Day
  month = (l.split()[+1] + '')  # Gets Month
  year = (l.split()[+3] + '')  # Gets Year
  time = (l.split()[+2] + '')  # Gets Time
  device = (l.split()[-2] + '')  # Gets Device
  Id = (l.split()[+9] + '')  # Gets  ID
  ap = (l.split()[+18] + '')  # Gets AP
  ApGroup = (l.split()[+19] + '')  # Gets AP Group
  MacAdd = (l.split()[+16] + '')  # Gets MAC
  #print (day, month, year, time, device, Id, ap, ApGroup, MacAdd)
  #insert line into db else by primary key (ID)
  #update line to db if ID doesn't exist
  #pringle = ['Dec', '11', '2018', '15:10:51', 'iPhone', '[jeref2]',
  #    'home', 'hm1', '45.88.34.58)\n']

  sql = "INSERT INTO SocketTest (month, day, year, time, device, Id, ap, ApGroup, MacAdd) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);"
  cur.execute(sql, (day, month, year, time, device, Id, ap, ApGroup, MacAdd))
  con.commit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM