for keys, values in data_frame.iterrows():
new_dict = {
'歌曲名': values['歌曲名'],
'歌手名': values['歌手名'],
'中央曲库ID': values['中央曲库歌曲ID']
}
if '伴奏' in str(values['歌曲名']):
sql = 'select song_id from songs_ip where center_inst_ids like "%s" ' \
'and company_id=4 and deleted_at is null;' % values['中央曲库歌曲ID']
else:
sql = 'select song_id from songs_ip where center_ids like "%s" ' \
'and company_id=4 and deleted_at is null;' % values['中央曲库歌曲ID']
cursor.execute(sql)
if cursor.fetchone():
print(cursor.fetchone())
song_id = cursor.fetchone()
print(song_id)
else:
print(0)
写了一串这样的代码,如果不判断cursor.fetchone()是否为空值,那么cursor.fetchone()可以打印出来,一旦判断之后全部为空不知道为什么.
cursor.fetchone() 只能执行一次,第一次可以先赋值
tmp = cursor.fetchone()
if tmp:
print(tmp )
song_id = tmp
print(song_id)
原因 是因为 cursor.fetchone() 每次执行游标就会往下移动一次。你这个sql 查出来应该只有一条数据。当if cursor.fetchone() 后相当于把数据取出来了,并且游标已经往下移动了。再次执行 cursor.fetchone() 会找第二条,但是现在又没有数据,所以返回了NONE ,自然就打印不出来了。更改的话,用1楼的方法可以,你可以看下源码
def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result
```python
```
已解决,需要将cursor.fetchone()的返回值先存起来,因为他会自动关闭