python中executemany和迭代器的应用

一 代码

import sqlite3
class IterChars:
    def __init__(self):
        self.count = ord('a')
    def __iter__(self):
        return self
    def __next__(self):
        if self.count>ord('z'):
            raise StopIteration
        self.count +=1
        return (chr(self.count-1))
conn=sqlite3.connect(":memory:")
cur=conn.cursor()
cur.execute("CREATE TABLE character(c)")
theIter = IterChars()
cur.executemany("INSERT INTO character(c) VALUES(?)",theIter)
cur.execute("SELECT c FROM character")
#cur.execute("DELETE FROM character")
print(cur.fetchall())

 

二 运行结果
y ========
[('a',), ('b',), ('c',), ('d',), ('e',), ('f',), ('g',), ('h',), ('i',), ('j',), ('k',), ('l',), ('m',), ('n',), ('o',), ('p',), ('q',), ('r',), ('s',), ('t',), ('u',), ('v',), ('w',), ('x',), ('y',), ('z',)]

猜你喜欢

转载自cakin24.iteye.com/blog/2386392
今日推荐