Python多线程存取MySQL数据


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

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

1.存入数据:

 1 import MySQLdb
 2 import datetime
 3 import time
 4 def insert(io):
 5     while True:
 6         time_now = datetime.datetime.now()
 7         print io,time_now
 8         conn = MySQLdb.connect(user = "root", passwd = "qwe123", host = "192.2.4.166", db = "python")
 9         cur = conn.cursor()
10         sql = "insert into table_%s values ('%s','%s');"
11         cur.execute(sql%(io,io,time_now))
12         cur.close()
13         conn.commit()
14         time.sleep(5)
15 
16 if __name__ == "__main__":
17     import threading
18     t = threading.Thread(target=insert,args=('in',))
19     t.start()
20     t = threading.Thread(target=insert,args=('out',))
21     t.start()
22     t.join()

2.读取数据:

 1 #coding *.* coding: utf-8 *.*
 2 import MySQLdb
 3 import time
 4 conn = MySQLdb.connect(
 5     host = "192.2.4.166",
 6     port = 3306,
 7     user = "root",
 8     passwd = 'qwe123',
 9     db = 'python',
10     #如果遇到数据库中有中文,加这条
11     charset = "utf8",
12 )
13 def read(io):
14     list = [0]
15     while True:
16         conn = MySQLdb.connect(user="root", passwd="qwe123", host="192.2.4.166", db="python")
17         # cursorclass 使输出变为字典形式
18         cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
19         sql = "select * from table_%s order by date desc;"
20         cur.execute(sql % io)
21         info = cur.fetchone()
22         if info not in list:
23             print info
24             list.append(info)
25             list.pop(0)
26         cur.close()
27         conn.commit()
28         time.sleep(2)
29 
30 if __name__ == "__main__":
31     import threading
32     t = threading.Thread(target=read, args=('in',))
33     t.start()
34     t = threading.Thread(target=read, args=('out',))
35     t.start()
36     t.join()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM