将Python中的Python列表插入SQL选项卡

2024-06-25 05:26:58 发布

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

我的代码从一个套接字读取并创建一个名为I的列表。套接字被读取,列表从套接字创建,列表被打印然后删除。这会在一个while true循环中重复。不只是打印列表,我想把它插入数据库的一个表中。我已经在代码中建立了游标和连接。我在搞别的东西,但总是出错。我想用REPLACE-INTO代替INSERT-INTO。非常感谢你的帮助。你知道吗

这是一个列表的示例。 '2018年12月11日,'12:28:43,'iPhone,'alpha,'lib,'lib,'(45.67.67)\n']

我的表名是StudentPrototype,它有7列 列-(日期、时间、设备、ID、AP、APGroup、MACAdd)

#!/bin/python

import socket
import os, os.path
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'pass', 
'StudentTacker');
cur = con.cursor()
cur.execute("SELECT VERSION()")
i = []





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
    # This is where I want to REPLACE INTO my table called StudentTest using list i


    print(i)

    del i[:]





if os.path.exists("/-socket"):
    os.remove("/-socket")

sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
sock.bind("/home/socket")
infile = sock.makefile('r')




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

更新:我尝试了在这个站点上找到的另一种方法,用于在数据库中插入python列表。你知道吗

下面是我在函数中使用的新代码:

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 FSU 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 mac adresss
#update line to db if mac adress doesn't exist
params = ['?' for item in i]
sql    = 'REPLACE INTO SocketTest (month, day, year, time, device, 
Id, ap, ApGroup, MacAdd) VALUES (%s); ' % ', '.join(params)
cur.execute(sql, i)

使用它我得到一个错误:

Traceback (most recent call last):
  File "./UnixSocketReader9.py", line 55, in <module>
ParseArray(l)
  File "./UnixSocketReader9.py", line 28, in ParseArray
cur.execute(sql, i)
  File "/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py", line 
  187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting

Tags: 代码in列表executeoslinesocketsock