使用 python 在 postgreSQL 表中插入元组值时出现错误

发布于 2024-08-31 08:44:22 字数 1827 浏览 4 评论 0原文

我想使用 pylast 接口将 last.fm 的用户最近的音乐曲目列表保留到 postgresql 数据库表中。但是当我尝试将值插入到表中时,它显示错误。代码示例:

import pylast
import psycopg2
import re
from md5 import md5
import sys
import codecs
import psycopg2.extensions

psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
user_name = raw_input("Enter last.fm username: ")
user_password = raw_input("Enter last.fm password: ")

api_key = '*********'
api_secret = '********'

#Lastfm network authentication
md5_user_password = md5(user_password).hexdigest()
network = pylast.get_lastfm_network(api_key, api_secret,user_name,md5_user_password)

used=pylast.User(user_name, network)

recent_tracks=used.get_recent_tracks(10)

# Database connection 
try:
    conn=psycopg2.connect("dbname='**' user='postgres' host='localhost'   password='*'")
    conn.set_client_encoding('UNICODE')
except:
    print "I am unable to connect to the database, exiting."
    sys.exit()
cur=conn.cursor()

for i, artist in enumerate(recent_tracks):
    for key in sorted(artist):

        cur.execute("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%s,%s,%s)""",  (key, artist[key]))

    conn.commit()
cur.execute("SELECT * FROM u_recent_track;")
cur.fetchone()
for row in cur:
    print '   '.join(row[1:])

cur.close()
conn.close()

这里“recent_tracks”元组的值例如:

artist 0
  - playback_date : 5 May 2010, 11:14
  - timestamp : 1273058099
  - track         : Brian Eno - Web

我想要将这些值存储在 u_recent_track(Tid, Playback_date, Time_stamp, Track) 下。有人知道如何解决这个问题吗?当我尝试运行时,它显示错误:

Traceback (most recent call last):
  File "F:\JavaWorkspace\Test\src\recent_track_database.py", line 50, in <module>
    VALUES (%s,%s,%s)""",  (key, artist[key]))
IndexError: tuple index out of range

I want to keep last.fm's user recent music tracks list to postgresql database table using pylast interface.But when I tried to insert values to the table it shows errors.Code example:

import pylast
import psycopg2
import re
from md5 import md5
import sys
import codecs
import psycopg2.extensions

psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
user_name = raw_input("Enter last.fm username: ")
user_password = raw_input("Enter last.fm password: ")

api_key = '*********'
api_secret = '********'

#Lastfm network authentication
md5_user_password = md5(user_password).hexdigest()
network = pylast.get_lastfm_network(api_key, api_secret,user_name,md5_user_password)

used=pylast.User(user_name, network)

recent_tracks=used.get_recent_tracks(10)

# Database connection 
try:
    conn=psycopg2.connect("dbname='**' user='postgres' host='localhost'   password='*'")
    conn.set_client_encoding('UNICODE')
except:
    print "I am unable to connect to the database, exiting."
    sys.exit()
cur=conn.cursor()

for i, artist in enumerate(recent_tracks):
    for key in sorted(artist):

        cur.execute("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%s,%s,%s)""",  (key, artist[key]))

    conn.commit()
cur.execute("SELECT * FROM u_recent_track;")
cur.fetchone()
for row in cur:
    print '   '.join(row[1:])

cur.close()
conn.close()

Here "recent_tracks" tuple have the values for example:

artist 0
  - playback_date : 5 May 2010, 11:14
  - timestamp : 1273058099
  - track         : Brian Eno - Web

I want to store these value under u_recent_track(Tid, Playback_date, Time_stamp, Track).Can anybody have idea how to sort out this problem? when I tried to run, it shows error:

Traceback (most recent call last):
  File "F:\JavaWorkspace\Test\src\recent_track_database.py", line 50, in <module>
    VALUES (%s,%s,%s)""",  (key, artist[key]))
IndexError: tuple index out of range

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小霸王臭丫头 2024-09-07 08:44:22

sorted(artist) 返回艺术家的有序列表,当您对其进行迭代时,它仍然返回 artist 的元素。因此,当您尝试访问artist[key]时,它实际上是在尝试访问由索引索引的artist元素,该元素是artist的元素本身。元组不是这样工作的。

看来您正在使用 python2.5 或更低版本,因此您可以这样做:

cur.executemany("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%(playback_date)s,%(timestamp)s,%(track)s)""",  recent_tracks)
conn.commit()

这应该可行。

sorted(artist) returns a ordered list of artist, when you're iterating over it it returns still elements of artist. So when you're trying to access artist[key] it is actually trying to access an element of artist indexed by the index, which is an element of artist itself. Tuples do not work this way.

It seems you're using python2.5 or lower and therefore you could do:

cur.executemany("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%(playback_date)s,%(timestamp)s,%(track)s)""",  recent_tracks)
conn.commit()

This should work.

压抑⊿情绪 2024-09-07 08:44:22

此错误与 Postgres 无关,而是与 artist 变量有关。您首先说:

for key in sorted(artist):

暗示它是一个列表,但随后您像访问字典一样访问它,这会引发错误。是哪一个?您能展示完整内容的示例吗?

This error isn't anything to do with Postgres, but with the artist variable. You're firstly saying:

for key in sorted(artist):

implying that it's a list, but then you're accessing it as if it were a dictionary, which is raising an error. Which is it? Can you show an example of the full contents?

浪漫人生路 2024-09-07 08:44:22

(Playback_date,Time_stamp,Track) 表示您要在一行中插入三个值。
因此,VALUES (%s,%s) 应为 VALUES (%s,%s,%s)
(key, Artist[key]) 应该是一个包含 3 个元素的元组,而不是 2 个。

尝试:

for track in recent_tracks:
    cur.execute("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%s,%s,%s)""",  (track.get_date(), track.get_timestamp(), track.get_track()))
    conn.commit()

PS。 这是我获取有关 pylast API 的信息的地方

聚苯硫醚。如果我对文档的阅读是正确的,track.get_track() 将返回一个 Track 对象。它具有诸如 get_albumget_artistget_idget_title 等方法。您究竟希望在 u_recent_track 数据库表的 Track 列中存储什么内容?

(Playback_date,Time_stamp,Track) indicates you want to insert three values into a row.
VALUES (%s,%s) should therefore be VALUES (%s,%s,%s)
and (key, artist[key]) should be a tuple with 3 elements, not 2.

Try:

for track in recent_tracks:
    cur.execute("""
        INSERT INTO u_recent_track(Playback_date,Time_stamp,Track) 
        VALUES (%s,%s,%s)""",  (track.get_date(), track.get_timestamp(), track.get_track()))
    conn.commit()

PS. This is where I'm getting my information about the pylast API.

PPS. If my reading of the documentation is correct, track.get_track() will return a Track object. It has methods like get_album, get_artist, get_id and get_title. Exactly what do you want stored in the Track column of the u_recent_track database table?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文