Python多线程存取MySQL数据

    xiaoxiao2021-03-25  67

    这两天正好接触python对sql的多线程问题,于是写了个demo以供参考。

    首先安装MySQLdb,指令是:pip install mysql-python

    1.存入数据:

    import MySQLdb import datetime import time def insert(io): while True: time_now = datetime.datetime.now() print io,time_now conn = MySQLdb.connect(user = "root", passwd = "qwe123", host = "192.2.4.166", db = "python") cur = conn.cursor() sql = "insert into table_%s values ('%s','%s');" cur.execute(sql%(io,io,time_now)) cur.close() conn.commit() time.sleep(5) if __name__ == "__main__": import threading t = threading.Thread(target=insert,args=('in',)) t.start() t = threading.Thread(target=insert,args=('out',)) t.start() t.join()

    2.读取数据:

    #coding *.* coding: utf-8 *.* import MySQLdb import time conn = MySQLdb.connect( host = "192.2.4.166", port = 3306, user = "root", passwd = 'qwe123', db = 'python', #如果遇到数据库中有中文,加这条 charset = "utf8", ) def read(io): list = [0] while True: conn = MySQLdb.connect(user="root", passwd="qwe123", host="192.2.4.166", db="python") # cursorclass 使输出变为字典形式 cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) sql = "select * from table_%s order by date desc;" cur.execute(sql % io) info = cur.fetchone() if info not in list: print info list.append(info) list.pop(0) cur.close() conn.commit() time.sleep(2) if __name__ == "__main__": import threading t = threading.Thread(target=read, args=('in',)) t.start() t = threading.Thread(target=read, args=('out',)) t.start() t.join()

    转载请注明原文地址: https://ju.6miu.com/read-39654.html

    最新回复(0)