创建多个游标

时间:2015-05-22 01:09:22

标签: python mysql

是否有做以下操作的简写?

    # need 3 cursors for reading and writing
    self.cursor1 = self.conn.cursor()
    self.cursor1.execute("SET NAMES utf8")
    self.cursor1.execute('SET CHARACTER SET utf8;')
    self.cursor1.execute('SET character_set_connection=utf8;')

    self.cursor2 = self.conn.cursor()
    self.cursor2.execute("SET NAMES utf8")
    self.cursor2.execute('SET CHARACTER SET utf8;')
    self.cursor2.execute('SET character_set_connection=utf8;')

    self.cursor3 = self.conn.cursor()
    self.cursor3.execute("SET NAMES utf8")
    self.cursor3.execute('SET CHARACTER SET utf8;')
    self.cursor3.execute('SET character_set_connection=utf8;')

基本上,我需要三个游标才能在脚本中进行阅读和写作,我希望能够做到这样的事情:

cursor_n = self.cursor1.clone()

如果存在类似的东西。

1 个答案:

答案 0 :(得分:1)

这样更好吗?

self.cursor = []
for n in range(3):
    self.cursor.append(self.conn.cursor())
    self.cursor[n].execute("SET NAMES utf8")
    self.cursor[n].execute('SET CHARACTER SET utf8;')
    self.cursor[n].execute('SET character_set_connection=utf8;')

或(我认为cursor()是一个类):

class my_cursor(self.conn.cursor):
    def __init__(self):
        self.execute("SET NAMES utf8")
        self.execute('SET CHARACTER SET utf8;')
        self.execute('SET character_set_connection=utf8;')

self.cursor1 = my_cursor()
self.cursor2 = my_cursor()
self.cursor3 = my_cursor()