使用 python 在 postgreSQL 表中插入元组值时出现错误
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
sorted(artist)
返回艺术家的有序列表,当您对其进行迭代时,它仍然返回artist
的元素。因此,当您尝试访问artist[key]
时,它实际上是在尝试访问由索引索引的artist
元素,该元素是artist的元素本身。元组不是这样工作的。
看来您正在使用 python2.5 或更低版本,因此您可以这样做:
这应该可行。
sorted(artist)
returns a ordered list of artist, when you're iterating over it it returns still elements ofartist
. So when you're trying to accessartist[key]
it is actually trying to access an element ofartist
indexed by the index, which is an element ofartist
itself. Tuples do not work this way.It seems you're using python2.5 or lower and therefore you could do:
This should work.
此错误与 Postgres 无关,而是与
artist
变量有关。您首先说:暗示它是一个列表,但随后您像访问字典一样访问它,这会引发错误。是哪一个?您能展示完整内容的示例吗?
This error isn't anything to do with Postgres, but with the
artist
variable. You're firstly saying: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?
(Playback_date,Time_stamp,Track)
表示您要在一行中插入三个值。因此,
VALUES (%s,%s)
应为VALUES (%s,%s,%s)
和
(key, Artist[key])
应该是一个包含 3 个元素的元组,而不是 2 个。尝试:
PS。 这是我获取有关 pylast API 的信息的地方。
聚苯硫醚。如果我对文档的阅读是正确的,
track.get_track()
将返回一个Track
对象。它具有诸如get_album
、get_artist
、get_id
和get_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 beVALUES (%s,%s,%s)
and
(key, artist[key])
should be a tuple with 3 elements, not 2.Try:
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 aTrack
object. It has methods likeget_album
,get_artist
,get_id
andget_title
. Exactly what do you want stored in theTrack
column of theu_recent_track
database table?