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

2024-06-12 08:53:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个列表,我正在将其插入一个名为SocketTest的SQL表中。基本上我在存储连接日志。我只想存储某人连接到的最后一个位置AP(接入点),而不是像我现在这样的一个列表。它们按时间顺序读取并通过套接字,因此我在函数中得到的最新列表始终是该用户最新的列表。基本上,我的程序从一个套接字读取数据,并用逗号分隔出一个列表,然后我将它插入到我的表中,当套接字中仍有信息时,它会不断重复。我的单子在《我的名字》里。我一直想自己弄清楚,但我没有经验。我想看看PK,它是ID,如果还没有存储ID,就插入一行;如果ID已经存在,则替换或更新存储的行。我正在寻找替换和插入重复的钥匙,但无法使它工作。感谢任何帮助,代码如下。

SocketTest是桌子: PK是ID: 普林格尔是一个例子:

编辑:我将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()

编辑:代码的其余部分

^{pr2}$

Tags: 代码id编辑列表dbsqllineap
2条回答

我将你的函数改写为:

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

如果您使用的是pymysql库,那么这样做可以:

row_to_insert = [val1, val2, val3]

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

更多信息可以在这里找到:How to use variables in SQL statement in Python?

海报评论后编辑:

^{pr2}$

相关问题 更多 >